原型
在 js 中我们使用构造函数来新建一个对象的,每一个构造函数的内部都有一个 prototype 属性值,这个属性值是一个对象, 这个对象包含了可以由该构造函数的所有实例共享的属性和方法。当我们使用构造函数新建一个对象后,在这 个对象的内部将包含一个指针, 这个指针指向构造函数的 prototype 属性对应的值,在 ES5 中这个指针被称为对象的原型。
下面一个小例子
function doSomething(){}
console.log( doSomething.prototype );
控制台输出
{
constructor: ƒ doSomething(),
__proto__: {
constructor: ƒ Object(),
hasOwnProperty: ƒ hasOwnProperty(),
isPrototypeOf: ƒ isPrototypeOf(),
propertyIsEnumerable: ƒ propertyIsEnumerable(),
toLocaleString: ƒ toLocaleString(),
toString: ƒ toString(),
valueOf: ƒ valueOf()
}
}
再上一张图
原型对象有一个自有属性constructor,这个属性指向该函数,如下图关系展示
原型链
当我们访问一个对象的属性时,如果这个对象内部不存在这个属性,那么它就会去它的原型对象里找这个属 性,这个原型对象又会有自己的原型,于是就这样一直找下去,也就是原型链的概念。
小例子
function Person(name) {
this.name = name;
this.age = 18;
this.sayName = function() {
console.log(this.name);
}
}
// 第二步 创建实例
var person = new Person('person')
下面分析一下:
- 构造函数
Person存在原型对象Person.prototype - 构造函数生成实例对象
person,person的__proto__指向构造函数Person原型对象 Person.prototype.__proto__指向内置对象,因为Person.prototype是个对象,默认是由Object函数作为类创建的,而Object.prototype为内置对象Person.__proto__指向内置匿名函数anonymous,因为 Person 是个函数对象,默认由 Function 作为类创建Function.prototype和Function.__proto__同时指向内置匿名函数anonymous,这样原型链的终点就是null