Javascript OOP - 继承,原型,回调函数 [英] Javascript OOP - inheritance, prototyping, callback function
本文介绍了Javascript OOP - 继承,原型,回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在Javascript中使用OOP与继承,原型和回调函数。请您查看我的JSfiddel http://jsfiddle.net/Charissima/5g6GV/ 。
第一个问题已在 Javascript OOP中得到解决 - 继承和原型,但不幸的是回调函数不再工作了。
I'm trying to use OOP in Javascript with inheritance, prototyping and callback functions. Would you please have a look at my JSfiddel http://jsfiddle.net/Charissima/5g6GV/. The first problem is solved already in Javascript OOP - inheritance and prototyping, but unfortunately the callback functions don't work any more.
function Car () {
this.totalDistance = 0;
};
Car.prototype.putTotalDistance = function(distance) {
this.totalDistance = distance;
};
Car.prototype.getTotalDistance = function() {
return this.totalDistance;
};
Car.prototype.drive = function(distance) {
this.totalDistance += distance;
return this.totalDistance;
};
function RaceCar () {};
RaceCar.prototype = new Car();
RaceCar.prototype.parent = Car.prototype;
RaceCar.prototype.drive = function(distance) {
return this.parent.drive.call(this, (distance * 2));
};
var myText;
car = new Car;
raceCar = new RaceCar;
car.putTotalDistance(200);
myText = 'car totalDistance = ' + car.drive(10) + ' - ok<br>';
raceCar.putTotalDistance(200);
myText += 'raceCar totalDistance before drive = ' + raceCar.getTotalDistance() + ' - ok<br>';
myText += 'raceCar totalDistance after drive = ' + raceCar.drive(10) + ' - ok<br><br>';
car.putTotalDistance(0);
raceCar.putTotalDistance(100);
var drivingFunctions = [car.drive, raceCar.drive];
myText += drivingFunctions[0](10) + '<br>';
try {
myText += drivingFunctions[1](100) + '<br>';
}
catch(err) {
myText += err + + '<br>'
}
document.body.innerHTML = myText;
推荐答案
所以当调用时, this
得到改变。
您可以使用函数 bind
:
You've put the two functions in an array, so when called, this
get changed.
You could use function bind
:
var drivingFunctions = [car.drive.bind(car), raceCar.drive.bind(raceCar)];
以下是一个帮助您理解的示例:
Here is an example to help you understand:
function Man(name){
this.name = name;
this.getName = function(){
return this.name;
};
}
var man = new Man('toto');
var a = [man.getName];
console.log(a[0]());//undefined
a.name = 'titi';
console.log(a[0]());//titi, because this refers to the array.
这篇关于Javascript OOP - 继承,原型,回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文