我不认为这是一个基于意见的问题,因为我要求的是“适当”的技术,而不是“最好的”技术或“您最喜欢的”技术。以下选项具有客观的权衡,我想知道处理原型定义和函数定义的行业标准方法是什么。
说我有很多apple
对象:
var newApple = function(){
return {
id: new guid(),
color: red
}
}
var apple = newApple();
我经常吃这些苹果并调用以下内容:
appleManager.eatApple(apple, fast)
但我想这样做:
var newApple = function(){
return {
id: new guid(),
color: red,
eat: function(speed){
// a bunch of logic here
}
}
然后打电话
apple.eat(fast);
但在我的脑海中,我想到的是所有functions
漂浮在周围占据空间的人,而在此之前只有一个函数实例。
我还想知道eat
在对象上定义eatApple(this, speed)
是否是一个更合适的选项——这样函数就在一个地方,我们只是从对象中引用它。
关于 javascript 对象上行为特定功能的定义,有哪些选项和客观权衡?例子将是花花公子。
这是使用@Potter 提到的原型链的示例。
function Apple(){
this.id = new guid();
this.color = 'red';
}
Apple.prototype = {
eat:function(speed) {
//do something
}
}
var apple = new Apple();
apple.eat('fast');
console.log(apple.color);//prints 'red'
该Apple
函数是一个构造函数。任何附加到this
指针并放入原型的东西都将被每个实例“继承”。
在 JavaScript 中,您可以使用原型链模拟经典继承。
function Fruit(color) {
this.color = color;
}
Fruit.prototype = {
eat:function() {
console.log('Eating some fruit.');
}
};
function Apple(color) {
Fruit.call(this, color);//Call the parent constructor function
this.isOnATree = true; //Add some new properties
}
Apple.prototype = Object.create(Fruit); //Inherit all parent methods
Apple.prototype.eat = function() { //Override parent eat method
console.log('Eating a' + this.color + ' apple');
};
var apple = new Apple('red');
apple.eat(); //Eating a red apple.
另外,我会推荐JavaScript the Good Parts。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句