Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

javascript - Why does a method's `this` change when calling a reference to an object's method?

function Person(gender) {
  this.gender = gender;
}

Person.prototype.sayGender = function()
{
  alert(this.gender);
};

var person1 = new Person('Male');
var genderTeller = person1.sayGender;

person1.sayGender(); // alerts 'Male'
genderTeller(); // alerts undefined

Why does genderTeller(); alerts undefined is not clear to me. if I see it I believe it's just same as line above it. Can some please explain the details

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you assign a variable like this...

var genderTeller = person1.sayGender;

...you lose the context of the person1 object, and the function's this points to the global object (window in a browser), instead of the instantiated person1 object.

You get undefined because the gender property does not exist on window, and referencing an undefined property on an object returns undefined in JavaScript.

You can fix that in modern browsers with bind()...

var genderTeller = person1.sayGender.bind(person1);

...or jQuery has a method too called proxy().

var genderTeller = $.proxy(person1.sayGender, person1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...