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ş:
Nasıl bir soyut temel sınıf uygulayan ...
Nasıl JavaScript iki boyutlu bir dizi ...
Nasıl temel bir UİButton programlı olu...
Nasıl Matematik için temel belirtebili...
Nasıl Zerofilled bir değeri JavaScript...