我遇到了在javascript中向对象添加方法的问题。以下代码应返回一个数字,而是返回NaN。希望你能帮忙
function people(name, age){
this.name = name;
this.age = age;
this.numYearsLeft = pension();
}
function pension(){
numYears = 65 - this.age;
return numYears;
}
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft);
答案 0 :(得分:5)
您可以使用原型模型 - 使pension
成为people
的方法:
function people(name, age){
this.name = name;
this.age = age;
this.numYearsLeft = this.pension(); // note the `this`
}
people.prototype.pension = function(){ // note the `prototype`
var numYears = 65 - this.age;
return numYears;
};
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft); // 37
使用prototype
您的pension
方法将继承构造函数(people
)属性(允许您使用this
关键字进行引用)。
这样做的另一个好处是,在new
people
的每个pension
实例化中,您都不会重新创建from multiprocessing import Process
import datetime
class foo:
def fun1():
do sthn
def fun2():
do sthn
ob = foo()
if __name__ == '__main__':
p1 = Process(target = ob.fun1)
p1.start()
p2 = Process(target = ob.fun2)
p2.start()
endTime=datetime.datetime.now()
print 'Program Ending time is: ', endTime
方法的新实例/召回。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
答案 1 :(得分:2)
JavaScript适用于“功能范围”,所以简而言之,你的范围是错误的。您需要绑定“this”变量或使用prototype属性在people类上创建一个函数。
您可以将其定义为原型函数
people.prototype.pension = function() {
numYears = 65 - this.age;
return numYears;
}
答案 2 :(得分:2)
如果在养老金中添加console.log()行,您会看到this
是窗口而不是人物对象。更改this
的一种方法是使用call()。
this.numYearsLeft = pension.call(this);
示例:
function people(name, age) {
this.name = name;
this.age = age;
this.numYearsLeft = pension.call(this);
}
function pension() {
numYears = 65 - this.age;
return numYears;
}
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft);

其他选择是让它成为人物原型的一部分。
function people(name, age) {
this.name = name;
this.age = age;
this.numYearsLeft = this.pension();
}
people.prototype.pension = function () {
numYears = 65 - this.age;
return numYears;
}
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft);

答案 3 :(得分:0)
为了调用函数,你需要put()。 console.log(andrews.numYearsLeft);
应为console.log(andrews.numYearsLeft());
同样在
function pension(){
numYears = 65 - this.age;
return numYears;
}
this.age未定义,因此是NaN。
(编辑)也许试试:
function people(name, age){
var that = this;
this.name = name;
this.age = age;
this.numYearsLeft = function(){
numYears = 65 - that.age;
return numYears;
};
}
var andrews = new people("Andrews Green", 28);
console.log(andrews.numYearsLeft());