gpt4 book ai didi

javascript - 在 Javascript 中返回未定义的函数

转载 作者:行者123 更新时间:2023-11-30 09:18:20 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com