【面向对象】new

一、new

function CreateCat(name){
    this.name = name;
}
var catA = new CreateCat('xiaoA');
console.log(catA.name)//xiaoA

new做了什么操作:

1. 创建一个空对象
2. 将构造函数的prototype属性赋值给新对象的__proto__属性
3. 将构造函数的this指向新对象
4. 执行构造函数的代码
5. 将新对象返回
var catB = (function(){
    var obj = {};
    obj.__proto__ = CreateCat.prototype;
    CreateCat.call(obj,'xiaoB');
    return obj;
})()
console.log(catB.name);//xiaoB

二、原型

在声明函数的时候,会自动创建一个prototy属性,叫做原型,用来存放实例公用的方法。
function CreateCat(name){
     this.name = name;
}
console.log(CreateCat.prototype)
// 输出

举例:

CreateCat.prototype.eat = function(something){
   console.log(this.name + ' eat ' + something + '.');//xiaoA eat fish.
}
var catA = new CreateCat('xiaoA');
catA.eat('fish');

此时 console.log(catA) 

原文地址:https://www.cnblogs.com/CarrotHu/p/12617178.html