JS中new与Object.create()的区别深入解析

[TOC]

在网上看了很多关于new与Object.create()的区别的文章,看的稀里糊涂的,各种说法的都有,看“你不懂的JS”那本书上也提到了这个,看的怀疑人生了。遂自己总结下认为比较说的通的一种理解。

  • 函数都有prototype,对象(包括函数)都有__proto__

new

1
2
3
4
5
6
7
8
9
10
function Test(){
this.a = 1;
}
Test.prototype.say = function() {
console.log(this.a);
}
var testA = new Test();
testA.a = 2;
delete testA.a;
console.log(testA.a);//undefined

new首先创建一个空对象testA,然后改变this调用Test构造函数,最后将新对象的浏览器属性__proto__指向Test的原型

1
2
3
var testA ={};
Test.apply(testA);
testA.__proto__ = Test.prototype;

Object.create()

1
2
3
4
5
6
7
8
9
function Test(){
this.a = 1;
}
Test.prototype.say = function() {
console.log(this.a);
}
var testB = Object.create(Test);
testB.a = 2;
console.log(testA.a);//打印 2


创建一个临时对象F,最终testB的__proto__指向Test构造函数


1
2
3
4
5
Object.prototype.create = function(Test){
var F = Function (){};
F.prototype = Test;
return new F();
}

感觉还是没彻底讲清楚。未完待续吧

热评文章