SORU
28 ŞUBAT 2009, CUMARTESİ


Nasıl JavaScript soyut temel sınıf oluşturabilirim?

Olası soyut temel sınıf simüle etmek için JavaScript mi? Bunu yapmak için en zarif yolu nedir?

Diyelim ki, gibi bir şey yapmak istiyorum: -

var cat = new Animal('cat');
var dog = new Animal('dog');

cat.say();
dog.say();

Çıkış: '', '' . miyav hav

CEVAP
19 Ocak 2014, Pazar


Soyut bir sınıf oluşturmak için basit bir yoludur bu

/**
 @constructor
 @abstract
 */
var Animal = function() {
    if (this.constructor === Animal) {
      throw new Error("Can't instantiate abstract class!");
    }
    // Animal initialization...
};

/**
 @abstract
 */
Animal.prototype.say = function() {
    throw new Error("Abstract method!");
}

7 ** "Sınıf" ve say soyut yöntem.

Bir örnek oluşturma hatası atar:

new Animal(); // throws

Bu nasıl bir "miras" ile

var Cat = function() {
    Animal.apply(this, arguments);
    // Cat initialization...
};
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

Cat.prototype.say = function() {
    console.log('meow');
}

Dog buna benziyor.

Ve bu senaryo nasıl sonuçlanacağını

var cat = new Cat();
var dog = new Dog();

cat.say();
dog.say();

Keman here (bak konsol çıkış).

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

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Amazon Web Services

    Amazon Web S

    8 NİSAN 2009
  • Charles Nesson

    Charles Ness

    27 NİSAN 2006
  • KliptOut KwazeeKilla

    KliptOut Kwa

    24 ŞUBAT 2010