SORU
10 Aralık 2011, CUMARTESİ


Neden prototip kurucu ayarlamak için gerekli mi?

section about inheritance in the MDN article Introduction to Object Oriented Javascript prototip hazırladılar fark ettim.kurucu:

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;  

Bu önemli bir amaca hizmet ediyor mu? Onu ihmal etmek olur mu?

CEVAP
10 Aralık 2011, CUMARTESİ


Her zaman gerekli değil, ama işe yarıyor. Person temel sınıf bir kopya yöntemi yapmak istediğimizi varsayalım. Bu gibi:

// define the Person Class  
function Person(name) {
    this.name = name;
}  

Person.prototype.copy = function() {  
    // return new Person(this.name); // just as bad
    return new this.constructor(this.name);
};  

// define the Student class  
function Student(name) {  
    Person.call(this, name);
}  

// inherit Person  
Student.prototype = Object.create(Person.prototype);

Şimdi Student yeni bir kopya yaratırsak ne olur?

var student1 = new Student("trinth");  
console.log(student1.copy() instanceof Student); // => false

Kopya Student değil bir örneğidir. Bu açık Çek olmadan), "" sınıf. taban Student bir kopyasını döndürmek için hiçbir biçimde olurdu çünkü Sadece Person geri dönüş yapabiliriz. Eğer olsaydı ancak, kurucu sıfırlama:

// correct the constructor pointer because it points to Person  
Student.prototype.constructor = Student;

...o zaman her şey beklendiği gibi çalışıyor

var student1 = new Student("trinth");  
console.log(student1.copy() instanceof Student); // => true

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Anthony Cumia

    Anthony Cumi

    5 EYLÜL 2006
  • fireflame65

    fireflame65

    27 Mart 2007
  • soyacincautv

    soyacincautv

    14 NİSAN 2010