programing tip

Javascript 생성자 속성의 중요성은 무엇입니까?

itbloger 2020. 7. 17. 20:57
반응형

Javascript 생성자 속성의 중요성은 무엇입니까?


OO에 대한 Javascript의 취임에 대해 머리를 구부리고 다른 많은 사람들과 마찬가지로 constructor속성 에 혼란을 겪고 있습니다. 특히, constructor나는 그것이 아무런 영향을 미치지 않는 것처럼 보이기 때문에 재산 의 중요성 . 예 :

function Foo(age) {
    this.age = age;
}

function Bar() {
    Foo.call(this, 42);
    this.name = "baz"; 
}

Bar.prototype = Object.create(Foo.prototype); 
var b = new Bar;    

alert(b.constructor); // "Foo". That's OK because we inherit `Foo`'s prototype.
alert(b.name);        // "baz". Shows that Bar() was called as constructor.
alert(b.age);         // "42", inherited from `Foo`.

위의 예에서 객체 b는 ( Bar) 라는 올바른 생성자를 가진 것으로 보이며 age 속성을 상속합니다 Foo. 그래서 많은 사람들이 왜 이것을 필요한 단계로 제안합니까?

Bar.prototype.constructor = Bar;

분명히, 생성시 올바른 Bar생성자 호출 b되었으므로이 프로토 타입 속성에 어떤 영향이 있습니까? 객체 생성 후 실제로 어떤 생성자가 호출되는지에 영향을 미치지 않으므로 생성자 속성을 '올바로'설정하는 데 실제로 어떤 실질적인 차이가 있는지 궁금합니다.


constructor숙소는 내부적으로는 실질적인 차이가 없습니다. 코드에서 명시 적으로 사용하는 경우에만 사용됩니다. 예를 들어, 객체를 생성 한 실제 생성자 함수에 대한 참조를 갖기 위해 각 객체가 필요하다고 결정할 수 있습니다. 그렇다면 예제와 같이 constructor생성자 함수의 prototype속성에 개체를 할당하여 상속을 설정할 때 속성을 명시 적으로 설정해야합니다 .


단계 하나를 이해하는 것입니다 constructorprototype모든하려고합니다. 어렵지는 않지만 고전적인 의미에서 "상속"을 놓아야합니다.

생성자

constructor속성 new 객체를 생성하기 위해 연산자와 함께 사용 된 함수를 확인할 수 있다는 점을 제외하고는 프로그램에서 특정 효과를 유발 하지 않습니다 . 입력 new Bar()하면 그대로 Bar입력 new Foo됩니다 Foo.

프로토 타입

prototype속성은 해당 개체가 속성을 요청하지 않는 경우 조회에 사용됩니다. 당신이 쓰는 경우 x.attr, 자바 스크립트를 찾기 위해 노력할 것 attr사이 x의 속성. 찾을 수 없으면를 찾습니다 x.__proto__. 그 중 하나가 아니라면, 그것은에 모양 x.__proto__.__proto__과 너무 오래로에 __proto__정의된다.

그래서 무엇 __proto__이며 무엇과 관련이 prototype있습니까? 간단히 말해서, prototype"유형"을 __proto__위한 것이고 "인스턴스"를위한 것이다. (타입과 인스턴스 사이에는 실제로 차이가 없기 때문에 따옴표로 말합니다). 당신이 쓸 때 x = new MyType()(다른 것들 중에서) 일어나는 일은 x.__proto___로 설정됩니다 MyType.prototype.

질문

이제, 당신 자신의 본이 의미하는 바를 도출하기 위해 필요한 것이지만, 실제 질문에 답하려고 노력하십시오. "같은 것을 쓰는 이유":

Bar.prototype.constructor = Bar;

나는 개인적으로 그것을 보지 못했고 조금 어리석은 것을 발견했지만, 당신이 주어진 맥락에서- Bar.prototype객체 (를 사용하여 new Foo(42)생성)가 Bar아닌에 의해 생성 된 것처럼 포즈를 취할 것임을 의미합니다 Foo. 타입 룩업 ( constructor속성)이 프로토 타입 체인에서 더 일반적인 객체의 유형보다 항상 가장 구체적인 유형을 생성하는 C ++ / Java / C # 유사 언어와 비슷한 것을 만드는 아이디어가 있다고 생각합니다. .

내 충고 : JavaScript의 "상속"에 대해 많이 생각하지 마십시오. 인터페이스와 믹스 인의 개념이 더 합리적입니다. 그리고 객체의 유형을 확인하지 마십시오. 필요한 속성을 대신 확인하십시오 ( "오리처럼 걷고 오리처럼 like 거리면 오리").

위에서 설명한 것처럼 프로토 타입 메커니즘 만 있으면 JavaScript를 고전적인 상속 모델로 만들려고하는 것이 혼란을 야기하는 것입니다. constructor-property 를 수동으로 설정하도록 제안한 많은 사람들이 아마도 그렇게하려고했습니다. 추상화는 괜찮지 만 생성자 속성을 수동으로 할당하는 것은 JavaScript의 관용적이지 않습니다.


생성자를 사용하는 경우 :

  1. 이것은 상속의 일반적인 실현 중 하나입니다.

    Function.prototype.extend = function(superClass,override) {
        var f = new Function();
        f.prototype = superClass.prototype;
        var p = this.prototype = new f();
        p.constructor = this;
        this.superclass = superClass.prototype;
        ...
    };
    
  2. 이것은 new f()superClass의 생성자를 호출하지 않으므로 하위 클래스를 만들 때 처음에 다음과 같이 superClass를 호출해야 할 수도 있습니다.

    SubClass = function() {
        SubClass.superClass.constructor.call(this);
    };
    

생성자 속성은 여기서 의미가 있습니다.


One of the use cases when you would want the prototype.constructor property to survive prototype property reassignment is when you define a method on the prototype that produces new instances of the same type as the given instance. Example:

function Car() { }
Car.prototype.orderOneLikeThis = function() {  // Clone producing function
    return new this.constructor();
}
Car.prototype.advertise = function () {
    console.log("I am a generic car.");
}

function BMW() { }
BMW.prototype = Object.create(Car.prototype);
BMW.prototype.constructor = BMW;              // Resetting the constructor property
BMW.prototype.advertise = function () {
    console.log("I am BMW with lots of uber features.");
}

var x5 = new BMW();

var myNewToy = x5.orderOneLikeThis();

myNewToy.advertise(); // => "I am BMW ..." if `BMW.prototype.constructor = BMW;` is not 
                      // commented; "I am a generic car." otherwise.

The constructor property points to the constructor that was used to create the object instance. If you typed 'new Bar()' it will be 'Bar' and you typed 'new Foo()' it will be 'Foo'.

But if you set the prototype without setting the constructor, you would get something like this:

function Foo(age) {
    this.age = age;
}

function Bar() {
    this.name = "baz"; 
}

Bar.prototype = new Foo(42); 
var one = new Bar();
console.log(one.constructor);   // 'Foo'
var two = new Foo();
console.log(two.constructor);   // 'Foo'

To set the constructor actually to the constructor that was used to create the object, we need to set the constructor as well while setting prototype as follows:

function Foo(age) {
    this.age = age;
}

function Bar() {
    this.name = "baz"; 
}

Bar.prototype = new Foo(42); 
Bar.prototype.constructor = Bar;
var one = new Bar();
console.log(one.constructor);   // 'Bar'
var two = new Foo();
console.log(two.constructor);   // 'Foo'

참고URL : https://stackoverflow.com/questions/4012998/what-it-the-significance-of-the-javascript-constructor-property

반응형