跳到主要内容

原型、原型链

  • __proto__ 只有对象才会有这个属性,__proto__ 就是对象的原型,通过它可以将原型串起来,形成原型链,原型链类似一个单向链表。
  • prototype 只有函数才会有这个属性,用于保存每个函数的原型对象。

原型就是一个普通对象,每个函数创建就会有这个属性,函数的实例对象可以通过 __proto__ 访问到;也可以直接通过 . 运算符直接访问,这种访问方式遵循原型链的访问规则(先看看自己有没有,没有就依次向上层原型对象上找,直到访问到 null,还没找到就返回 undefined)

原型链

  1. function Function(){}函数的 __proto__ 和 prototype都指向 Function.prototype
  2. Object.ptototype 的 __proto__ 是 null
  3. 所有函数的实例对象都访问不到 Function.prototype
function Person(name, age) {
this.name = name;
this.age = age;
}

var person = new Person("person", 25);

// person {} --> Person.prototype --> Object.prototype --> null
console.log(person.__proto__ === Person.prototype);
console.log(person.__proto__.__proto__ === Object.prototype);
console.log(person.__proto__.__proto__.__proto__ === null);

// Person fn --> Function.prototype --> Object.prototype --> null
console.log(Person.__proto__ === Function.prototype);
console.log(Person.__proto__.__proto__ === Object.prototype);
console.log(Person.__proto__.__proto__.__proto__ === null);

// Function fn --> Function.prototype --> Oject.prototype --> null
console.log(Function.__proto__ === Function.prototype);
console.log(Function.__proto__.__proto__ === Object.prototype);
console.log(Function.__proto__.__proto__.__proto__ === null);

var obj = {};
// {} --> Object.prototype --> null
console.log(obj.__proto__ === Object.prototype);
console.log(obj.__proto__.constructor === Object);
console.log(obj.__proto__.__proto__ === null);

原型链是控制访问对象属性的一个规则,作用域链是控制访问变量的规则