function people (name, age) {
this.name = name;
this.age = age;
}
var rob = new people("robert jr", 41);
var sam = new people("sam davies", 25);
function isOlderThan(age) {
if(rob.age > sam.age)
return true;
else return false;
}
我试着用这个 sam.isOlderThan(rob) 运行它;
但它不起作用。我对此有点陌生,有什么帮助吗?
最佳答案
// If you want to be able to call this as sam.isOlderThan()
// you need to use a prototype to add that function to the persons
// so they all have that function bound to them.
function person (name, age) {
this.name = name;
this.age = age;
}
person.prototype.isOlderThan = function( other_person ) {
return this.age > other_person.age;
};
var rob = new person("robert jr", 41);
var sam = new person("sam davies", 25);
console.log( sam.isOlderThan( rob ) );
console.log( rob.isOlderThan( sam ) );
关于javascript - 在 Javascript 中返回未定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53448588/