原型和原型链

2018-04-23  本文已影响25人  lang_liu

创建对象的几种方式

使用字面量或 Object 方式创建

const obj = {name: 'allen'};
const obj1 = new Object({name: 'allen'});

使用显式的构造函数创建

const User = function() {
  this.name = 'allen';
}
const user = new User();

使用 Object.create() 创建

const obj = {name: 'allen'};
const user = Object.create(obj);

原型链

原型链.png
const User = function() {
  this.name = 'allen';
}
const user = new User();
console.log(User.prototype.constructor === User); // true

函数也有 __proto__ 属性,那是为什么呢?因为函数既是函数也是一个对象。函数默认是 Function 构造函数生成的一个实例对象

const User = function() {
  this.name = 'allen';
}
console.log(User.__proto__ === Function.prototype); // true

在调用实例的方法时,根据该实例的原型链一级一级的向上查找,直到找到 Object.prototype 如果还没有找到的话则调用失败,如果在某一级找到后停止向上查找。

instanceof

instanceof.png

instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。

const User = function() {
  this.name = 'allen';
}
const user = new User();
console.log(user instanceof User); // true
console.log(user instanceof Object); // true

new 运算符

new运算符.png
上一篇 下一篇

猜你喜欢

热点阅读