jQuery是否提供API来调用将this
变量绑定到jQuery对象的函数?例如:
function log() {
console.log(this);
}
$('body').execute(log); // prints the $('body') object in the console
我知道这可以通过将日志作为插件来解决,但我不想这样做,因为我需要调用的函数是泛型的,我不想将其绑定到jQuery。
编辑:
jQuery没有execute
方法,它只是我添加的一个片段,用来演示我想要实现的目标。
编辑2:
我不是问如何解决这个问题( API已经覆盖了我),我只是问jQuery是否已经提供了类似的underscore.js。
发布于 2011-12-21 18:54:02
您可以“不”使用jQuery来实现任何东西,只需稍微“翻转”一下,并使用函数名.apply (object, arguments)
function func (arg1, arg2) {
console.log ("ARG1: " + arg1);
console.log ("ARG2: " + arg2);
console.log ("using this: " + this.html ().length + "\n");
}
func.apply ($('body'), ['abc','123']);
func.apply ($('body')); // 2nd argument is optional
输出
ARG1: abc
ARG2: 123
using this: 51645
ARG1: undefined
ARG2: undefined
using this: 51645
发布于 2011-12-21 18:54:11
在你的作用域中,this
不会是你想要的那样。不过,您可以使用带参数的匿名函数:
function log($this) {
console.log($this);
}
$('body').execute(function() { log($(this)); }); // prints the $('body') object in the console
发布于 2011-12-21 19:45:59
看看这个:
$.fn.prototype.execute = function() {
var f = function(){ console.log(this)};
$.proxy( f , this )()
// that means something like
// f.call(this)
}
假设你有一个函数:
var f= function( arg1, arg2){
console.log(this, arg1, arg2)
}
在那里,您可以调用传递上下文和参数的f
f.call(document.body, arg1,arg2);
或参数作为apply
方法的数组
f.apply(document.body, [arg1,arg2]);
在这两种情况下,您都会得到
>> <body>...</body>, valOfarg1, varOfarg2
https://stackoverflow.com/questions/8594832
复制相似问题