Beispiel für Javascript Duck Typing?

Einige Programmierer raten von der Verwendung der pseudo-klassischen Vererbung in Javascript ab, raten jedoch von der Verwendung der Duck-Typing-Funktion und der Bereitstellung einer Reihe von Funktionen für jedes Objekt.

Gibt es ein gutes Beispiel dafür, wie das gemacht wird? Ich habe unten ein Beispiel, aber es wird immer nur eine Funktion zugewiesen. Können wir einem Objekt eine ganze Gruppe von Methoden zuweisen, wie zum Beispiel einen Prototyp vonOceanAnimal das kann "schwimmen", "tauchen" und "steigen", ein Prototyp vonLandAnimal für "rennen", "laufen" und "springen" und ein Objekt von einem oder beiden erben lassen? (Damit ein Fischobjekt die Fähigkeiten von erben oder erhalten kannOceanAnimalund eine Schildkröte kann die Fähigkeiten von beiden bekommenOceanAnimal undLandAnimal?)

var yoyo = {
    name: "Yoyo",
    type: "turtle"
}

var simba = {
    name: "Simba",
    type: "lion"
}

var dolphy = {
    name: "Dolphy",
    type: "dolphin"
}

function swim(n) {
    console.log("My name is", this.name, ", I am a", this.type, "and I just swam", n, "feet")
}

function run(n) {
    console.log("My name is", this.name,  ", I am a", this.type, "and I just ran", n, "feet")
}

Object.prototype.respondTo = function(method) {
    return !!(this[method] && (typeof this[method] === "function"));
}

yoyo.swim = swim;
yoyo.swim(10);

dolphy.swim = swim;
dolphy.swim(80);

simba.run = run;
simba.run(200);

yoyo.run = run;
yoyo.run(2);

yoyo.walk = run;
yoyo.walk(1);

console.log(simba.respondTo("swim"));
console.log(simba.respondTo("run"));
console.log(simba.respondTo("walk"));

console.log(yoyo.respondTo("run"));
console.log(yoyo.respondTo("walk"));
console.log(yoyo.respondTo("fly"));

if(dolphy.respondTo("run")) {
    dolphy.run(10);
}

if(dolphy.respondTo("swim")) {
    dolphy.swim(10);
}

Ausgabe:

My name is Yoyo , I am a turtle and I just swam 10 feet 
My name is Dolphy , I am a dolphin and I just swam 80 feet 
My name is Simba , I am a lion and I just ran 200 feet 
My name is Yoyo , I am a turtle and I just ran 2 feet 
My name is Yoyo , I am a turtle and I just ran 1 feet 
false 
true 
false 
true 
true 
false 
My name is Dolphy , I am a dolphin and I just swam 10 feet

Antworten auf die Frage(3)

Ihre Antwort auf die Frage