javascript:定义"this"在函数的上下文中
javascript: Defining "this" in the context of a function
当jQuery调用一个函数作为引发事件的事件处理程序时,jQuery以某种方式能够在它调用的函数上下文中定义"this"。在下面的例子中,jQuery将this定义为被点击的dom元素。
<input id="someButton" type="button" value="click me!"/>
<script type="text/javascript">
$("#someButton").click(EventHandler);
function EventHandler()
{
alert($(this).attr("id")); //This raises an alert message "someButton"
}
</script>
jQuery如何做到这一点?我想复制这种行为为我自己的自定义框架。
Function
有两个方法可以使用:call和apply。使用这两种方法,将想要用于this
的对象作为第一个参数传递。使用call
时,附加参数将依次传递:
functionName.call(this, arg1, arg2);
使用apply
,传入参数数组:
functionName.apply(this, [arg1, arg1]);
或者,您可以传递一个实际的参数对象:
function someFunction ()
{
functionName.apply(this, this.arguments);
}
您可以使用call
或apply
JavaScript方法:
function myFunction() {
// you want "this" to be your element
}
var element = SOMEDOMELEMENT;
myFunction.call(element, /* add other comma-separated arguments here, if any */);
myFunction.apply(element, /* add an array of arguments here, if any */);
当使用call和apply时,它会将函数内的上下文(this
)更改为您想要的任何元素
都是闭包
Javascript在定义像this
这样的变量时使用了闭包。
所以你可以这样做:
var myFuncs = {
func1: function(){
this.func2 = function() { alert('hello');}
return this;
},
func2: function(){alert('HI')}
}
所以如果你这样做了:
myFuncs.func1().func2(); // alerts 'hello'
而:
myFuncs.func2(); // alerts 'HI'
常规的旧javascript/html也可以。
<button id='something' onclick='alert(this.id);'>Click me</button>
不知道jQuery使用什么,但有一个bind
函数:
var regularFunc = function() {
console.log(this);
};
var boundFunc = regularFunc.bind(123);
regularFunc(); // logs whatever 'this' is at time it is called (e.g. 'window')
boundFunc(); // logs 123 at all times since that is specified to be 'this'
相关文章:
- 将函数的上下文应用于javascript变量
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 铬:“;未捕获的语法错误:意外的标记:"
- 使用JQuery的动态上下文菜单
- 可以设置“;文件名"发生错误时显示的内联脚本标记的
- JS表单提交"无法使用Chrome数据保护程序加载此页面.尝试重新加载页面.调试信息:POST CISmtuK
- 检测电话窃听,即:<a href="电话:xxx">在UIWebview上
- 使用“+="操作人员
- 如何访问UIWebView'的子窗口上下文
- //而不是在src=“”上使用http://"属性
- "未捕获的语法错误:意外的标记}"
- 可以<脚本类型=“;text/javascript”>window.location=“/"</
- "实例范围”;TypeScript类的getter/setter
- Javascript复选框函数:;缺少:在属性id之后"
- "“;变量未引用正确的对象
- "日期“;AJAX请求返回的类型值未定义
- 得到"TypeError:无法读取属性'filename'未定义的“;调用“npm start
- Soundcloud api"未捕获的类型错误:无法读取属性'uri'“未定义”;
- RequireJS中的动态require,得到"尚未加载上下文“”的模块名称;错误
- "上下文”;Firebase.on的参数不起作用