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

原型链.png


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

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

new

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 log.png

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

new.png
var testA ={};
Test.apply(testA);
testA.__proto__ = Test.prototype;

Object.create()

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
create log.png

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

create.png

Object.prototype.create = function(Test){
    var F = Function (){};
    F.prototype = Test;
    return new F();
}

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容