如何将一个方法连接到不同的对象

how to connect one method to diffrent objects?

本文关键字:连接 对象 方法 一个      更新时间:2023-09-26

你能为我介绍一下我在学习Javascript中的对象和原型时遇到的练习吗?

让我们只说,我必须创建一个简单的食物链与3种动物(猫鸟蠕虫)。

它应该以如下输出的方式实现3个对象(所有对象都应该实现相同的方法"吃"):

    var cat1 = Object.create(Cat);
var cat2 = Object.create(Cat);
var bird = Object.create(Bird);
var worm = Object.create(Worm);
cat1.eat(bird); // "Tasty!"
cat2.eat(bird); // "Tasty!"
bird.eat(worm); // "Tasty!"
worm.eat(cat1); // "Bleeh!"
cat1.eat(cat2); // "Bleeh!"

所以当我创建对象时:

var Cat  = {
   eat = function(){}
};
var Bird = {
   eat = function (){}
};
var Worm = {
   eat = function (){}
};

我应该把"if"语句放在哪里,以确定何时返回正确的值?(猫吃鸟,鸟吃虫,鸟不能吃鸟等)还有其他方法可以写一种吃所有动物的方法吗?

一种方法是定义Animal"class",它是JS中的一个函数(至少在ES5中是这样)。然后,您可以创建Cat"类",它将继承Animal类,并在其中定义它吃什么。eat函数将是Animal类中的一个通用函数,这样您就不必每次都用不同的值覆盖它。

var Animal = function() {
    this.canEat = [];
}
Animal.prototype.eat = function (animal) { 
    if (this.canEat && this.canEat.indexOf(animal) !== -1) {
        console.log('Yum!'); 
    }
    else {
        console.log('Bleh!');
    }
};
var Cat = function() {
    this.canEat = ['bird'];
}
// Inheritance
Cat.prototype = Object.create(Animal.prototype);
var cat = new Cat();
cat.eat('bird');  // Yum!
cat.eat('cat');   // Bleh!

Fiddle

您必须以正确的方式组织对象,并且必须进行继承。

var Animal = {
  // set food chain hierarchy
  // worm -> 1, birds -> 2, cat -> 3, lion -> 4
  level: 0,
  eat: function(otherAnimal) {
    return this.level > otherAnimal.level ? 'Tasty':'Bleeh';
  },
  init: function(level){
    this.level = level;
    return this;
  }
};
var cat1 = Object.create(Animal).init(3);
var cat2 = Object.create(cat1);
var bird = Object.create(Animal).init(2);
var worm = Object.create(Animal).init(1);
cat1.eat(bird); // "Tasty!"
cat2.eat(bird); // "Tasty!"
bird.eat(worm); // "Tasty!"
worm.eat(cat1); // "Bleeh!"
cat1.eat(cat2); // "Bleeh!"

工作Fiddle

function Organism(){};
function Cat(){};
function Bird(){};
function Worm(){};
Organism.prototype.eat = function(food){
    if(this.level > food.level){
        console.log('Tasty!');
    } else {
        console.log('Bleeh!');
    }
}
Cat.prototype = new Organism();
Cat.prototype.level = 3;
Bird.prototype = new Organism();
Bird.prototype.level = 2;
Worm.prototype = new Organism();
Worm.prototype.level = 1;
var cat1 = new Cat();
var cat2 = new Cat();
var bird = new Bird();
var worm = new Worm();
cat1.eat(bird); // "Tasty!"
cat2.eat(bird); // "Tasty!"
bird.eat(worm); // "Tasty!"
worm.eat(cat1); // "Bleeh!"
cat1.eat(cat2); // "Bleeh!"