[英]how to use the method correctly in js?
<script>
function Person(gender) {
this.gender = gender;
}
Person.prototype.sayGender = function()
{
alert(this.gender);
};
var person1 = new Person('Male');
var genderTeller = person1.sayGender;
genderTeller();
</script>
Question: 题:
It shows 'undefined'. 它显示'未定义'。 what is the problem with the script? 脚本有什么问题?
你需要在person1
的范围内调用它
genderTell.call(person1);
Evan is right. 埃文是对的。 The scope is window
when you call the function. 调用该函数时,范围是window
。 You need to call it on the person. 你需要在这个人身上打电话。 When you retrieve the function like that you only get the function, not the scope. 当您检索函数时,您只获得函数,而不是范围。
This also works instead: 这也适用于:
function Person(gender) {
this.gender = gender;
}
Person.prototype.sayGender = function () {
alert(this.gender);
};
var person1 = new Person('Male');
person1.sayGender(); // <-- calling the function ON "person1" directly
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.