0
<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?

4

2 回答 2

2

你需要在范围内调用它person1

genderTell.call(person1);

于 2013-06-14T01:21:10.253 回答
0

埃文是对的。范围是window您调用该函数的时间。你需要打电话给那个人。当您像这样检索函数时,您只会得到函数,而不是范围。

这也适用:

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

小提琴

于 2013-06-14T01:30:53.783 回答