IT박스

자바 스크립트 상속 : Object.create vs New

itboxs 2020. 7. 14. 20:57
반응형

자바 스크립트 상속 : Object.create vs New


JavaScript에서이 두 예제의 차이점은 무엇입니까?

전제 조건 :

function SomeBaseClass(){
}

SomeBaseClass.prototype = {
    doThis : function(){
    },

    doThat : function(){
    }
}

Object.create를 사용하는 상속 예제 A :

function MyClass(){
}

MyClass.prototype = Object.create(SomeBaseClass.prototype);

새 키워드를 사용한 상속 예제 B

function MyClass(){
}

MyClass.prototype = new SomeBaseClass();

두 예제 모두 같은 일을하는 것 같습니다. 언제 다른 것을 선택하겠습니까?

추가 질문 : 함수 자체 생성자에 대한 참조가 프로토 타입에 저장되는 아래 링크 (15 행)의 코드를 고려하십시오. 이것이 왜 유용한가요?

https://github.com/mrdoob/three.js/blob/master/src/loaders/ImageLoader.js

발췌 (링크를 열지 않으려는 경우) :

THREE.ImageLoader.prototype = {

    constructor: THREE.ImageLoader
}

귀하의 질문에서 당신은 Both examples seem to do the same thing``그것은 사실이 아닙니다.

첫 번째 예

function SomeBaseClass(){...}
SomeBaseClass.prototype = {
    doThis : function(){...},
    doThat : function(){...}
}
function MyClass(){...}
MyClass.prototype = Object.create(SomeBaseClass.prototype);

이 예에서, 당신은 상속을하고 SomeBaseClass' prototype있지만 당신이 SomeBaseClass좋아 하는 속성을 가지고 있다면

function SomeBaseClass(){ 
    this.publicProperty='SomeValue'; 
}

당신이 그것을 사용하면

var obj=new MyClass();
console.log(obj.publicProperty); // undefined
​console.log(obj);​

The obj object won't have publicProperty property like in this example.

Your second example

MyClass.prototype = new SomeBaseClass();

It's executing the constructor function, making an instance of SomeBaseClass and inheriting the whole SomeBaseClass object. So, if you use

    var obj=new MyClass();
    console.log(obj.publicProperty); // SomeValue
    console.log(obj);​

In this case its publicProperty property is also available to the obj object like in this example.

Since the Object.create is not available in some old browsers, in that case you can use

if(!Object.create)
{
    Object.create=function(o){
        function F(){}
        F.prototype=o;
        return new F();
    }
}

Above code just adds Object.create function if it's not available so you can use Object.create function and I think the code above describes what Object.create actually does. Hope it'll help in some way.


Both examples seem to do the same thing.

That's true in your case.

When would you chose one over the other?

When SomeBaseClass has a function body, this would get executed with the new keyword. This usually is not intended - you only want to set up the prototype chain. In some cases it even could cause serious issues because you actually instantiate an object, whose private-scoped variables are shared by all MyClass instances as they inherit the same privileged methods. Other side effects are imaginable.

So, you should generally prefer Object.create. Yet, it is not supported in some legacy browsers; which is the reason you see the new-approach much too frequent as it often does no (obvious) harm. Also have a look at this answer.


The difference becomes obvious if you use Object.create() as it is intended. Actually, it does entirely hideout the prototype word from your code, it'll do the job under the hood. Using Object.create(), we can go like

var base =  {
    doThis : function(){
    },

    doThat : function(){
    }
};

And then we can extend/inherit other objects from this

var myObject = Object.create( base );
// myObject will now link to "base" via the prototype chain internally

So this is another concept, a more "object oriented" way of inherting. There is no "constructor function" out of the box using Object.create() for instance. But of course you could just create and call a self defined constructor function within those objects.

One argument for using Object.create() is that it might look more natural to mix/*inherit* from other objects, than using Javascripts default way.


I am not an expert in java script but here is a simple example to understand difference between "Object.create" and "new" ..

step 1 : create the parent function with some properties and actions..

function Person() {

this.name = 'venkat';

this.address = 'dallas';

this.mobile='xxxxxxxxxx'

}

Person.prototype.func1 = function () {

    return this.name + this.address;
}

step 2 : create a child function (PersonSalary) which extends above Person function using New keyword..

function PersonSalary() {
    Person.call(this);
}
PersonSalary.prototype = new Person();

PersonSalary();

step 3 : create second child function (PersonLeaves) which extends above Person function using Object.create keyword..

function PersonLeaves() {
 Person.call(this);
}
PersonLeaves.prototype = Object.create(Person.prototype);


PersonLeaves();

// Now check both child functions prototypes.

PersonSalary.prototype
PersonLeaves.prototype

both of these child functions will link to Person(parent function) prototype and can access it's methods but if you create child function using new it will return a brand new object with all parent properties which we don't need and also when you create any object or function using "New" that parent function is executed which we don't want to be.

Here are the takeaways

if you just want to delegate to some methods in parent function and don't want a new object to be created , using Object.create is best way.

참고URL : https://stackoverflow.com/questions/13040684/javascript-inheritance-object-create-vs-new

반응형