Javascript 复习笔记

150 阅读1分钟

原型

参考文章:JavaScript深入之从原型到原型链

基本概念

  • 原型是指那些提供共享属性的对象,原型与其构造函数互相引用。
  • 访问对象属性时,会沿着原型链查找,直到原型为 null 时返回 undefined。
  • 原型、构造函数、实例三者之间的关系,图解: JS 原型图解.jpg

原型的代码解释

  • ES6 版本,Object.getPrototype 接受的参数是“对象”,返回对象的原型。
  • class 语法糖生成的是一个函数对象,所以 Object.getPrototype(function) 返回的是 Function.prototype
class Person {
    constructor(name) {
        this.name = name;
    }
}
const person = new Person('xiaocai');
console.log(Object.getPrototypeOf(person) === Person.prototype); // true
console.log(Object.getPrototypeOf(Person) === Function.prototype); // true
console.log(Object.getPrototypeOf(person) === Object.getPrototypeOf(Person)); // false
  • ES5 版本,访问原型:function.prototype / object.__proto__
function Person(name) {
    this.name = name;
}
var person = new Person('xiaocai');

console.log(person.__proto__ === Person.prototype); // true
console.log(Person.prototype.constructor === Person); // true
console.log(Person.prototype.__proto__ === Object.prototype); // true