SORU
28 EKİM 2009, ÇARŞAMBA


JavaScript: Sınıf.yöntem vs Sınıf.prototip.yöntem

Aşağıdaki iki bildirimleri arasındaki fark nedir?

Class.method = function () { /* code */ }
Class.prototype.method = function () { /* code using this.values */ }

Statik bir yöntem, ve bir örnek yöntemi ilanı olarak ikinci ifadeyi ilan ilk deyim sence sorun olmaz mı?

CEVAP
28 EKİM 2009, ÇARŞAMBA


Evet, ilk işlevi constructor function, öyle bir düşünün ki, bir nesne örneği ile hiçbir ilişkisi yoktur< . em ^'statik yöntem'.

Bu durumda herhangi bir nesne gibi davranmasını demektir first-class nesneleri, JavaScript işlevleri, tek bir özellik eklemiş olursunuzfonksiyon nesne.

İkinci işlev olarak size uzanan yapıcı fonksiyon prototipi, satışa sunulacak tüm nesne örnekleri ile oluşturulan new anahtar kelime, ve bu bağlamda bu işlevi (this anahtar kelime) için başvuruda bulunan gerçek nesne örneğini nerede diyorsun.

Örnek:

// constructor function
function MyClass () {
  var privateVariable; // private member only available within the constructor fn

  this.privilegedMethod = function () { // it can access private members
    //..
  };
}

// A 'static method', it's just like a normal function 
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};

MyClass.prototype.publicMethod = function () {
  // the 'this' keyword refers to the object instance
  // you can access only 'privileged' and 'public' members
};

var myObj = new MyClass(); // new object instance

myObj.publicMethod();
MyClass.staticMethod();

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

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • GirlSanctuaryBlog

    GirlSanctuar

    28 Aralık 2011
  • merumputdotcom

    merumputdotc

    24 ŞUBAT 2012
  • PlayStation

    PlayStation

    16 Aralık 2005