js new的理解

function Cat(name, color){

  this.name = name;

  this.color = color;

}

Cat.prototype.type = "猫科动物";

Cat.prototype.eat = function(){alert("吃老鼠");}

var cat1 = new Cat('大毛', '黄色');

var cat2 = new Cat('二毛', '黑色');

new的过程包含以下几步:

1. var obj = {};

2. obj.__proto__ = Cat.prototype;

3. var res = Cat.apply(obj, arguments);

4. return res==='object'?res:obj;

所以,cat1和cat2的__proto__指向Cat.prototype, 不同的对象实例共享类的所有属性及方法,同时可以拥有各自的差异属性

原文地址:https://www.cnblogs.com/taojunlong/p/6833125.html