原型
- 每个对象都有原型,原型里存着对象的共有属性和方法
obj.__proto__
存着obj的原型的地址,这个对象里有 toString/constructor/valueOf 等属性- 对象的原型也是对象,所以对象的原型也有原型
obj = {}
的原型为Object.prototype
即为所有对象的原型,这个原型的原型是null对象.__proto__ === 其构造函数的prototype
:构造函数使用自己的原型作为原型构造对象__ptoto__
与 prototype 的区别:__ptoto__
是对象的属性,prototype 是 构造函数的属性
构造函数
构造函数就是 制造对象工厂
- 构造函数名的首字母要大写
- 通过对象的 constructor 属性查看其构造函数
- 系统自带构造函数 :Object(), Array() …
自定义构造函数:
// new X() 自动做了四件事:
// 1. 创建空对象
// 2. 为这个空对象关联原型,原型地址为 X.prototype
// 3. 使用 this 指向这个空对象,运行构造函数
// 4. 自动 return this
function Zhuzhu(age) {
/* var this = {
__ptoto__: Zhuzhu.prototype;
};
或
var this = Object.create(Zhuzhu.prototype); 以Zhuzhu.prototy为原型创建对象
*/
this.age = age;
this.weight = 80kg;
// return this;
}
Zhuzhu.prototype.sleep = function() {
console.log('Zhuzhu is sleeping!');
};
Zhuzhu.prototype.eat = function() {
console.log('Zhuzhu is eating!');
}
Zhuzhu1 = new Zhuzhu(18);
Zhuzhu2 = new Zhuzhu(2);
构造函数 X 的作用:
- 构造函数 X 本身负责给对象本身添加属性
- X.prototype 对象负责保存构造函数 X对象的公用属性
- 构造函数 X 本身负责给对象本身添加属性
zhuzhu1.__proto__ === Zhuzhu.prototype
原型链
Object.prototype === zhuzhu1.__proto__.__proto__ === Zhuzhu.prototype.__proto__
zhuzhu1.toString === zhuzhu1.__proto__.__proto__.toString
Object 与 Function
- Object 与 Function 都是函数
- 普通对象是 Object 创造的,Object.prototype 是所有对象的直接或间接原型
- 任何函数都是由 Function 创造的
- Function 创造了 Function
Function.prototype === fn.__proto__ // true
({}).constructor === Object // true
Object.constructor === Function // true
Class 语法
写法有点像 javaclass Zhuzhu{ //class首字母小写
static lovely = true;
constructor(age) {
this.age = age;
}
age18() {
console.log('zhuzhu is always 18');
}
}
let zhuzhu = new Zhuzhu(18);
zhuzhu.age18;