知识点
1, 只要是函数就有 prototype
,__proto__
, 只要是对象就有 __proto__
属性
对象无 prototype 属性
构造函数有 proto prototype 属性.png
2, 通过构造函数
可以创建实例对象
,实例对象
的 __proto__
指向 构造函数
的 prototype
_proto_
作用是指向其构造函数的prototype , 且构造函数的prototype
是一个对象
注意是
构造函数的prototype
,而非构造函数,因此在创建构造函数时,如果要添加属性方法只能添加到 构造函数的prototype
上,实例对象才能被继承
3,函数的 prototype
属性中有constructor
,该属性指向函数本身
通过创建实例对象解释原型链
- var obj = {} 方法创建
var obj = {}
console.log(obj.__proto__ === Object.prototype)
console.log('Object.prototype', Object.prototype)
console.dir(Object.prototype.__proto__)
结果如下:
原型链为:
- 通过构造函数创建对象和函数的原型链
- 1 对象
function Person (name, age) { this.name = name; this.age = age; } var person1 = new Person('张三', 14) console.log(person1)
如图:
原型链为:
- 2 函数
var fn = new Function()
console.dir(fn)
打印结果:
原型链:
- 3 Object.create(Obj) 创建对象
实现原理:
Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
_相当于创建一个实例对象, 对象的 __proto__
指向的是传入的参数(即对象本身),而不是 对象的prototype
_
var ob = {}
var aaa = Object.create(ob)
console.log(aaa)
console.log(aaa.__proto__ === ob)
console.log(ob.__proto__ === Object.prototype)
原型链图:
补充
var aa = function () {}
console.log(aa.prototype.__proto__ === aa.__proto__.__proto__) // true
// 可以把实例函数 aa.prototype 看做 { constructor: aa,__proto__:Obeject.prototype对象 }