我有一个物体,在这个例子中是一个法拉利。当使用ferrari.speed = 90;
来改变速度时,我希望这个属性能够对变化做些什么,例如使用函数改变屏幕法拉利的速度。
我想知道最简单,最不疯狂的做法是什么?
这是一个jsfiddle:
<button id="addspeed">speed up!!</button>
<button id="checkspeed">Check the speed!</button>
function car(){
speed: 0;
//Do something about speed change here? if its changed at all, greater or smaller?
}
document.getElementById('addspeed').onclick = function speedchange(){
ferrari.speed++;
}
document.getElementById('checkspeed').onclick = function checkspeed() {
alert(ferrari.speed);
}
var ferrari = new car();
ferrari.speed = 10;
答案 0 :(得分:2)
Set operator
正是您要找的https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/set
这是我的解决方案http://jsfiddle.net/qhV7B/6/。
function car(){
}
car.prototype = {
hidden_speed: 0,
set speed(v){
//special action
alert("I changed value to " + v);
this.hidden_speed = v;
},
get speed(v){
return this.hidden_speed;
},
};
var ferrari = new car();
ferrari.speed = 10;
document.getElementById('addspeed').onclick = function speedchange(){
ferrari.speed = (ferrari.speed + 1);
}
document.getElementById('checkspeed').onclick = function checkspeed() {
alert(ferrari.speed);
}
答案 1 :(得分:1)
可以通过getter和setter完成,一种方法是通过Object.defineProperty():
function car(){
this._speed=0;
}
...
var ferrari = new car();
Object.defineProperty(car.prototype,"speed",{
get:function(){return this._speed;},
set:function(v){
this._speed=v;
document.getElementById("speed").textContent=v.toString(10);
}
});
ferrari.speed = 10;
关于getter和setter的其他文档,可能会或可能不会过时和/或依赖于平台:
*编辑:将Object.defineProperty
的参数从ferrari
更改为car.prototype
答案 2 :(得分:0)
此代码使用setSpeed
方法,允许您添加速度更改时所需的任何其他逻辑:
var Car, ferrari,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Car = (function() {
function Car() {
this.setSpeed = __bind(this.setSpeed, this);
}
Car.prototype.speed = 0;
Car.prototype.setSpeed = function(newSpeed) {
this.speed = newSpeed;
//Here is where you custom logic needs to run
return alert("Speed Changed to: " + this.speed);
};
return Car;
})();
ferrari = new Car();
ferrari.setSpeed(10);
document.getElementById('addspeed').onclick = function speedchange(){
ferrari.setSpeed(ferrari.speed+1);
}
document.getElementById('checkspeed').onclick = function checkspeed() {
alert(ferrari.speed);
}
答案 3 :(得分:0)
在评论中使用asawyers建议你可以创建一个speedUp函数,可以在更改时触发你的动画函数(如果你想减速,可以触发speedChange,无论你的船是什么漂浮)。
查看小提琴:http://jsfiddle.net/86HtX/
我还对你的代码进行了一些调整:
function car(){
var car = this;
this.speed = 0;
this.speedUp = function(mph){
car.speed += mph;
car.animate();
};
this.animate = function(){
alert(car.speed); // new speed
};
//Do something about speed change here? if its changed at all, greater or smaller?
}
document.getElementById('addspeed').onclick = function speedchange(){
ferrari.speedUp(1); // go 1 mph faster
}
document.getElementById('checkspeed').onclick = function checkspeed() {
alert(ferrari.speed);
}
var ferrari = new car();
ferrari.speed = 10;