如何使用Javascript或Jquery实现以下场景?
创建工厂以创造不同类型的动物 例如蛇,狮子,老虎,鱼,鸟等 他们每个人都来自阶级动物 动物基类具有一些属性,每个派生类都有特定动物特有的特殊方法 例如fish.swim(),bird.fly(),snake.crawl(),lion.run()等。
ui显示左侧有一个下降值,有3个值(陆地,水和空气) 在选择价值时,右侧应显示适当的动物(例如水=>鱼,空气=>鸟,土地=>蛇,狮子)我可以理解我可以在这里使用Prototype或Observer模式,但我坚持正确的实现。但仍然对正确的方法感到困惑,即使我进入了某些东西,编码明智,我也被卡住了。
答案 0 :(得分:1)
这是一个基本的类结构。请仔细阅读评论以获得解释。正如其他人所说,阅读addy ossmani的书将是一个很好的来源,可以帮助你更彻底地理解OOP。
// Base class
function Vehicle(type, wheeltype, noun, medium) {
this.type = type
this.wheeltype = wheeltype
this.noun = noun
this.medium = medium
}
Vehicle.prototype = {
// doing is declared on Vehicle as it's common to all child classes which all
// delegate to the same function
doing: function() {
return `I love ${this.noun} my ${this.color} ${this.type} on the ${this.medium}`
}
}
function Car(model, color) {
// run the constructor function passing in the current
// objects context
Vehicle.call(this, 'car', 4, 'driving', 'street')
// set properties on the Car
this.model = model
this.color = color
}
// This extends the Vehicle class
Car.prototype = new Vehicle
// this method is unique to Car
Car.prototype.drive = function() {
return `cruisin' down the ${this.medium} in my ${this.model}`
}
// you could use the class syntax
class Ship extends Vehicle {
constructor(model, color) {
// super calls the constructor with the context already set
super('boat', 0, 'sailing', 'ocean')
this.model = model
this.color = color
}
// unique method for a Ship
sail() {
return `I'm on a ${this.type} mother f**ker`
}
}
class JetSki extends Vehicle {
constructor(model, color) {
super('jetski', 0, 'riding', 'ocean')
this.model = model
this.color = color
}
ride() {
return `I'm on a ${this.type} mother f**ker`
}
}
// create objects from your constructors
var car = new Car('sixfaw', 'green')
var ship = new Ship('Riviera', '24 carot gold')
var jetski = new JetSki('Seadoo', 'green')
console.log('car.doing() ->', car.doing())
console.log('car.drive() ->', car.drive())
console.log('ship.doing()->', ship.doing())
console.log('ship.sail() ->', ship.sail())
var vehicles = [car, ship, jetski]
function filterByMedium(medium, vehicles) {
return vehicles.filter(function(vehicle) {
return vehicle.medium === medium
})
}
console.log(
filterByMedium('ocean', vehicles)
)