原型和原型链

原型链图

__proto__ , prototype , constructor

function Cat(){} 
var cat1 = new Cat; 

console.log(cat1.prototype) //false
console.log(Cat.prototype) //true
//实例对象没有prototype属性
//构造函数有一个prototype属性

new一个对象(实例化对象)时都发生了什么?

  1. 创建一个新对象

  2. 将构造函数的作用域赋给新对象(构造函数内默认会有 return this)

  3. 执行构造函数中的代码(为新对象添加属性)

  4. 返回该对象

构造函数

 用来初始化新创建的对象的函数叫做构造函数。例子中Cat()函数是构造函数,构造函数函数名通常大写

实例对象

 通过构造函数的new操作创建的对象是实例对象。可以用一个构造函数,构造多个实例对象

原型对象及prototype

 构造函数有一个prototype属性,指向实例对象的原型对象。通过同一个构造函数实例化的多个对象具有相同的原型对象。
 函数才有prototype属性,对象没有

主要使用原型来实现继承

function Cat(){};
Cat.prototype.type ='animal';
var cat1 = new Cat;
var cat2 = new Cat();

console.log(Cat.prototype.type);//animal
console.log(cat1.type);//animal
console.log(cat2.type);//animal

constructor

 原型对象有一个constructor属性,指向该原型对象对应的构造函数
function Cat(){};
console.log(Cat.prototype.constructor === Cat);//true
由于实例对象可以继承原型对象的属性,所以实例对象也拥有constructor属性,同样指向原型对象对应的构造函数
function Cat(){};
var cat1 = new Cat();
console.log(Cat.prototype.constructor === Cat);//true
console.log(cat1.constructor == Cat.prototype.constructor);//true
console.log(cat1.constructor === Cat); //true

__proto__

 实例对象有一个__proto__属性,指向该实例对象对应的原型函数
console.log( cat1.__proto__ === Cat.prototype );//true

参考:https://www.cnblogs.com/xiaohuochai/p/5721552.html

Last updated

Was this helpful?