简体   繁体   中英

Using Object.create() to develop a prototype chain

I have seen people writing this when want to extend another class:

Test2.prototype = Object.create( Test1.prototype );

But I did this too:

Test2.prototype = Test1.prototype;

And works (at least in the following example):

var Teste1 = function() 
{
    this.value = 'Teste1';
}
Teste1.prototype = {
    value:'no-class',
    print:function()
    {
        console.log( this.value );
    }
}

var Teste2 = function()
{
    Teste1.apply( this );
}
Teste2.prototype = Teste1.prototype;

var t = new Teste2();
t.print();

The console prints Teste1 , which means Teste1 constructor was called. The real questions are:

Why do we need use Object.create when extending classes in javascript? Will I get a problem with this idea of code in the future on the project?

thanks.

The difference between

Test2.prototype = Object.create( Test1.prototype );

and

Test2.prototype = Test1.prototype;

is that in the first example, you're creating a new object that uses Test1.prototype as its prototype. In the second example, you're just pointing the Test2.prototype property at the same object that Test1.prototype points to.

This has important ramifications, specifically that if you add properties via your Test2.prototype reference:

Test2.prototype.newProperty = 42;

...with the first example you don't end up changing the object Test1.prototype points to, but in the second example, you do, because both Test2.prototype and Test1.prototype are pointing to the same object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM