Inhaltsverzeichnis
Das Verständnis über Duck Typing in ECMAScript
View more Tutorials:


Bevor ich eine Definition von "Duck Typing" gebe, möchte ich Sie die Definition Interface in die Programmierungssprache sagen.
Interface ist ein Begriff in einigen Programmierungssprachen, z.B Java, Csharp ... Eine Interface wird die Liste seiner Methode anmelden. Dieses Method hat keine Inhalt (keinen Körper). Die Klasse für die Implementation dieser Interface muss alle Methode haben, die in Interface mit der ganzen Inhalt angemeldet werden. (Achtung: Hier erwähne ich die abstrakten Klassen nicht).



Die Nachteile vom Duck Typing:
OK, ECMAScript hat kein Begriff von Interface. Hier habe ich eine Klasse Duck (Ente). Sie hat 2 Methode walk() & fly().
class Duck {
fly() {
console.log("Duck fly");
}
walk() {
console.log("Duck walk");
}
}
class Airplane {
fly() {
console.log("Airplane fly");
}
walk() {
console.log("Airplane walk");
}
shoot(target) {
console.log("Airplane shoot " + target);
}
}
class Cat {
walk() {
console.log("Cat walk");
}
}
class Duck {
fly() {
console.log("Duck fly");
}
walk() {
console.log("Duck walk");
}
}
class Airplane {
fly() {
console.log("Airplane fly");
}
walk() {
console.log("Airplane walk");
}
shoot(target) {
console.log("Airplane shoot " + target);
}
}
class Cat {
walk() {
console.log("Cat walk");
}
}
let duck1 = new Duck();
let airplane1 = new Airplane();
let cat1 = new Cat();
function checkDuck(testObj) {
if(typeof testObj.fly == "function" && typeof testObj.walk == "function" ) {
return true;
}
return false;
}
// Array
let testArray = [duck1, airplane1, cat1];
for( let i = 0; i < testArray.length; i++) {
let testObj = testArray[i];
if( checkDuck(testObj) ) {
testObj.fly();
}
}
Duck fly
Airplane fly
var duck = {
type: "bird",
cry: function duck_cry(what) {
console.log(what + " quack-quack!");
},
color: "black"
};
var someAnimal = {
type: "bird",
cry: function animal_cry(what) {
console.log(what + " whoof-whoof!");
},
eyes: "yellow"
};
function check(who) {
if ((who.type == "bird") && (typeof who.cry == "function")) {
who.cry("I look like a duck!\n");
return true;
}
return false;
}
check(duck); // true
check(someAnimal); // true
I look like a duck!
quack-quack
I lock like a duck!
whoof-whoof