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
358 views
in Technique[技术] by (71.8m points)

How to modify "this" in javascript

I find myself wanting to re-define "this" many times through the day. Could someone please tell me how to achieve this or why I cannot?

For example:

this = $('div')[0];

Why i would like to do this: working with 'this' is more natural then passing a reference through a function call. 'this' should refer to the calling object inside of a function for example:

var my_div = $('#some_div');
my_div.click(function(){
    console.log(this);
});

What gets sent to the log is a reference to the window not to the div that is calling the function.

Every onchange event handler I write is forced to take 'this' as a parameter in order to maintain reference to the calling object. To me this seems broken.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use .call(context[, params])and .apply(context[, arguments]) to do this. For example:

function move(x, y) {
    this.style.left = x + "px";
    this.style.top = y + "px";
};

// now this in move refers to the div element
move.call($('div')[0], 100, 200);

But you can't just overwrite this.


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

...