0
点赞
收藏
分享

微信扫一扫

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

小迁不秃头 2021-09-30 阅读 49
JSjs基础


在网上看了很多关于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首先创建一个空对象testA,然后改变this调用Test构造函数,最后将新对象的浏览器属性__proto__指向Test的原型

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

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

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

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

举报

相关推荐

0 条评论