【发布时间】:2013-03-20 15:57:52
【问题描述】:
我目前正在学习 jQuery,并且刚刚开始实现 "this" 关键字。我了解它在 jQuery 中的作用,但它在 javascript 中是否具有与作用域引用相同的功能?
【问题讨论】:
标签: javascript jquery
我目前正在学习 jQuery,并且刚刚开始实现 "this" 关键字。我了解它在 jQuery 中的作用,但它在 javascript 中是否具有与作用域引用相同的功能?
【问题讨论】:
标签: javascript jquery
this 不是什么 jQuery 魔法,它是一个 JavaScript 关键字。
【讨论】:
this到底可以用来做什么?有时我尝试实现它,但发现它返回错误的值/变量/元素。
是的,JavaScript 中的this 关键字仍然表示当前范围内的元素。
【讨论】:
简短的解释:this 是一个函数的上下文,它可以根据调用该函数的方式而改变。例如:
function myfunc() {
console.log(this.toString());
}
myfunc(); //=> [object Window]
myfunc.call('Hello World'); //=> Hello World
使用原型时,this 指的是当前实例。在 jQuery 中,它的工作原理是这样的(非常简化):
(function(win) {
// Constructor
function jQuery(selector) {
}
// Shortcut to create news instances
function $(selector) {
return new jQuery(selector);
}
// Public methods
jQuery.prototype = {
// All methods 'return this' to allow chaining
// 'this' is the jQuery instance
method: function() {
return this;
}
};
win.$ = $; // expose to user
}(window));
因此,当您这样做 $(this) 时,您只是创建了一个新的 jQuery 实例,该实例包含 this 所指的任何内容(通常是一个 DOM 元素),因此您可以继承原型并使用公共方法。
【讨论】: