對象創(chuàng)建的三種方式:
1.字面量方式
2.調用系統(tǒng)的構造函數(shù)
3.自定義構造函數(shù)
<script type="text/javascript">
// 字面量方式
var per1 = {
name: "看看",
age: 20,
sex: "男",
eat: function() {
console.log("卡卡卡");
}
};
// 調用系統(tǒng)構造函數(shù)
var per2 = new Object();
per2.name = "加急";
per2.age = 30;
per2.sex = "男";
per2.play = function() {
console.log("愛媽媽");
};
//自定義構造函數(shù)
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
this.play = function() {
console.log("啊啊女")
}
}
var per3 = new Person("家啊", 30, "男");
console.log(per3 instanceof Person);
</script>
創(chuàng)建對象
實例化一個對象凫海,的同時進行初始化
工廠模式和自定義構造函數(shù)
- 共同點:都是函數(shù)扼菠,都可以創(chuàng)建對象,都可以傳入參數(shù)
- 工廠模式:
函數(shù)名是小寫,
有new
有返回值
new
之后的對象是當前的對象
直接調用函數(shù)就可以創(chuàng)建對象 - 自定義構造函數(shù)
函數(shù)名是大寫(首字母)
沒有new
沒有返回值
this
是當前的對象
通過new
的方式來創(chuàng)建對象
function creatObject(name, age) {
var obj = Object();
obj.age = age;
obj.name = name;
obj.sayMe = function() {
console.log("方法");
}
return obj;
}
// 創(chuàng)建對象----實例化一個對象,的同時進行初始化
function Person(name, age) {
this.name = name;
this.age = age;
this.sayMe = function() {
console.log("方法啊")
};
}
構造函數(shù)和實例對象的區(qū)別
1.實例對象是通過構造函數(shù)來創(chuàng)建的---創(chuàng)建的過程叫實例化
2.如何判斷對象是不是這個數(shù)據(jù)類型?
- 1)通過構造器的方式祭钉,實例對象.構造器==構造函數(shù)的名字
- 2)對象
instanceof
構造函數(shù)的名字
盡可能的使用第二種方式來識別
通過原型來添加方法,解決數(shù)據(jù)共享,節(jié)省內存空間
<script type="text/javascript">
function Person(name, age) {
this.name = name;
this.age = age;
}
// 通過原型來添加方法,解決數(shù)據(jù)共享,節(jié)省內存空間
Person.prototype.eat = function() {
console.log("總成績按揭");
}
var p1 = new Person("安靜", 20);
var p2 = new Person("信息", 30);
console.log(p1.eat == p2.eat); //true
console.dir(p1);
console.dir(p2);
</script>
原型
- 實例對象中有
__proto__
這個屬性,叫原型己沛,也是一個對象慌核,這個屬性是給瀏覽器使用,不是標準的屬性--->__proto__
--->可以叫原型對象 - 構造函數(shù)中有prototype這個屬性申尼,叫原型垮卓,也是一個對象,這個屬性是給程序員用的,是標準的屬性--->
prototype
-->可以叫原型對象
實例對象的__proto__
和構造函數(shù)中的prototype
相等师幕,--->ture
又因為實例對象是通過構造函數(shù)來創(chuàng)建的粟按,構造函數(shù)中有原型對象prototype
實例對象的__proto__
指向了構造函數(shù)的原型對象prototype
- 原型的作用:
共享數(shù)據(jù),節(jié)省內存空間
三者的關系
- 構造函數(shù)可以實例化對象
- 構造函數(shù)中有一個屬性叫
prototype
,是構造函數(shù)的原型對象 - 構造函數(shù)的原型對象(
prototype
)中有一個constructor
構造器霹粥,這個構造器指向的就是自己所在的原型對象所在的構造函數(shù) - 實例對象的原型對象(
__proto__
)指向的是該構造函數(shù)的原型對象 - 構造函數(shù)的原型對象(
prototype
)中的方法是可以被實例對象直接訪問的
利用原型共享數(shù)據(jù)
- 什么樣子的數(shù)據(jù)是需要寫在原型中灭将?
需要共享的數(shù)據(jù)就可以寫原型中 - 原型的作用之一:數(shù)據(jù)共享
- 不需要共享的數(shù)據(jù)寫在構造函數(shù)中,
- 原型對象中的方法,可以相互調用
- 實例對象使用的屬性或方法后控,先在實例中查找庙曙,找到了則直接使用,找不到則去實例對象的
__proto__
指向的原型對象prototype
中找浩淘,找了了則調用捌朴,找不到則報錯
簡單的原型寫法
<script type="text/javascript">
function Student(name, age) {
this.name = name;
this.age = age;
}
// 簡單的原型寫法
Student.prototype = {
constructor: Student,
height: "111",
weight: "55kg",
stydy: function() {
console.log("買奶粉嗎");
}
};
var stu = new Student("安監(jiān)局", 20);
stu.stydy();
console.dir(Student);
console.dir(stu);
console.log(Student);
</script>
- 相關代碼:
demo地址