如何使用Javascript或Jquery实现以下场景?
创建工厂来创建不同类型的动物,如蛇、狮子、老虎、鱼、鸟等,它们都是从类动物派生而来的,基类具有某些属性,每个派生类都有特定动物特有的方法,如fish.swim()、bird.fly()、snake.crawl()、lion.run()等。
ui显示左边有3个值(陆地、水和空气)的下降值,右侧应该显示合适的动物(如水=>鱼、空气=>鸟、陆地=>蛇、狮子)。
我可以理解,我可以在这里使用原型或观察者模式,但我被适当的实现困住了。但是仍然对正确的方法感到困惑,即使我进入了一些事情,编码明智,我还是被困住了。
发布于 2017-05-31 12:26:08
这是一个基本的类结构。请仔细阅读这些评论以获得解释。正如其他人所说,阅读addy的书将是帮助您更彻底地理解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)
)
https://stackoverflow.com/questions/44245095
复制相似问题