jquery/ javascript中self的用途是什么?
What is use of self in jquery/ javascript?
在javascript中,他们使用的是:
-
var self=this;
-
var jquery_element= $(html_element);
-
self.jquery_element=jquery_elemnet
为什么我们在javascript中使用这些呢?这段代码来自OpenStack horizon
var self=this;
是有用的,当你有嵌套函数和this
可以变得模棱两可(如果你不知道this
是一个javascript关键字)。self
仍然可以用来改变this
,现在从内部函数指向this
。
var jquery_element= $(html_element);
只是提供了一种简单的方法来引用jQuery元素,而不必经常重新创建它(也提供了性能优势,例如这里解释的)。
self.jquery_element = jquery_element
似乎是特定于该代码,我不太确定它的作用
这是为了在其他范围内可见,在一个范围内使用this
。编辑。
var parentFunction = function(){
this.msg = "hello world";
var parentScopeSelf = this;
var innerFunction = function(){
var innerFunctionScopeSelf = this;
console.log(this.msg);// undefined (because this now is innerFunction scope, and does not have property msg)
console.log(innerFunctionScopeSelf.msg);// undefined (because innerFunctionScopeSelf is "this" from innerFunction scope, and does not have property msg)
console.log(parentScopeSelf.msg);// hello world (because parentScopeSelf is "this" from parentFunction scope)
}
}
回答你的直接问题,this
是一个javascript 关键字,它的值会根据它的位置而改变。通过将其值写入像self
这样的常规变量,即使this
本身发生了变化,也可以保留self
在范围内的值。
当您有嵌套函数时,将this
分配给另一个变量是有用的。例如:
jQuery(function($) {
$('#myInput').on('keyup', function() {
var $this = $(this); // assign the jQuery's element to $this
$('div.errors').each(function() {
console.log($(this)); // outputs jQuery's object div.errors
console.log($this); // the input is still available in the nested function
});
});
});
作为建议,如果变量存储jQuery
元素,请在其前面加上$
。因此,它应该是
var $jquery_element = $(html_element);
var jquery_element= $(html_element);
是使HTML元素成为一个jquery对象,可以使用jquery的所有方法。
html_element.fadeOut();
<——将不工作
$(html_element).fadeOut();
<——将工作
相关文章:
- 这是什么 ==- javascript 运算符
- 我的单元测试选项是什么
- 打破承诺链的好方法是什么
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- Javascript中的空白是什么
- 是什么让一个“;Uncaught RangeError:超过了最大调用堆栈大小“;错误(Chrome,在其他浏览器中显示
- 在JavaScript中拆分日期字符串的更好方法是什么
- 将jQuery.ech()方法转换为本地JavaScript抽象的最佳方法是什么
- 处理浮点错误的最佳方法是什么
- javascript导入的最佳实践是什么
- 基于窗口宽度jquery的函数的替代方法是什么
- 在ng重复循环中显示条件内容的最佳方式是什么
- 我的客户端选项是什么
- 这是什么“;要求“;事情
- 未捕获的类型错误:topFrame.window.changeSelectedBarStyle不是函数,原因是什么
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- “var self = this”方法背后的原理是什么?
- “var self = module.exports;”是什么意思
- 在self.setInterval中,jquery关键字self-referred指的是什么?jquery
- jquery/ javascript中self的用途是什么?