图解原型链
一、prototype 和 _proto_
在大多数情况下,_proto_ === constrcutor.prototype

二、函数 与 对象 的原型
这里要注意,任何函数(包括构造函数Function)都是Object的实例(Object代表原生对象的构造函数)
function fn() {};
console.log(fn instanceof Function); // true
console.log(Function instanceof Object); // true
console.log(fn instanceof Object ); // true
console.log(fn === fn.prototype.constructor) // true

var o = {};
console.log(o.__proto__ === o.constructor.prototype) // true
console.log(o.__proto__ === Object.prototype) // true
console.log(o instanceof Object); // true

三、构造器原型链
1、声明构造函数Animal
function Animal(name) {
this.name = name || 'Animal';
this.sleep = function() {
console.log(this.name + '正在睡觉');
}
}
Animal.prototype.eat = function(food) {
console.log(this.name + '正在吃' + food || '东西')
}
var ani = new Animal('dog');
console.log(ani.__proto__ === ani.constructor.prototype) // true
console.log(ani instanceof Animal) // true
console.log(ani instanceof Object) // true

2、声明构造函数Cat,并将其原型prototype设为构造函数Animal的实例
function Cat() {}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';
var cat = new Cat();
console.log(cat.__proto__ === cat.constructor.prototype) // false
console.log(cat.constructor.prototype === Animal) // false
console.log(cat.__proto__.__proto__.constructor === Animal) // true
console.log(cat.__proto__.constructor === Animal) // true (cat.__proto__ 继承 cat.__proto__.__proto__ 的属性)
console.log(cat.constructor === Animal) // true (cat 继承 cat.__proto__ 的属性)
console.log(cat instanceof Cat) // true
console.log(cat instanceof Animal) // true
cat.eat() // cat正在吃东西

参考链接:https://www.cnblogs.com/shuiyi/p/5305435.html
原型制作链接:https://www.processon.com/

浙公网安备 33010602011771号