这里有一个小提琴:为什么`foo()`在这里工作?
https://jsfiddle.net/5k10h27j/
为什么当设置作为参数传递给未定义功能无法foo()
被调用?
function foo(){
alert('huh??');
}
jQuery('#container').on('change', 'input', function(e){
console.log('change');
}).blahblah(foo());
这里有一个小提琴:为什么`foo()`在这里工作?
https://jsfiddle.net/5k10h27j/
为什么当设置作为参数传递给未定义功能无法foo()
被调用?
function foo(){
alert('huh??');
}
jQuery('#container').on('change', 'input', function(e){
console.log('change');
}).blahblah(foo());
在尝试定位未定义的函数之前调用该函数。
在表达等
objectReference.propertyName(arg1, arg2, arg3)
该语言的标准规定的参数被评估之前的任何测试,以确定该函数的参考是否实际上是有效的。因此,您在参数列表中对foo()
的调用将被评估,并且只有在其值已知之后才会进行任何测试,以查看属性参考是否属于实际函数。
Here is the relevant portion of the spec.第3步是对参数的评估,第4步是测试以确定代码称为函数的东西实际上是函数。
首先,您需要在某处定义您的blahblah函数,并且它必须原型jQuery才能用于链接。一旦用回调参数定义了函数,就可以通过传递foo引用而不是函数调用来调用它。
$.fn.blahblah = function (callback) {
callback();
return this; // if you want to keep chaining
};
function foo() {
alert('huh??');
}
$('#container')
.on('change', function() {
console.log('change');
})
.blahblah(foo);
// in this case you can keep chaining since blahblah is returning 'this'.
我想操作意味着知道它为什么会提示'呃?'即使功能blahblah不存在。像'为什么'会在下面的代码中提醒:'window.yesIKThisThisDoesNotExistButAlerts(function(){alert('why');}())' – HMR 2015-03-31 01:53:13
代码应该**在这里发布**。 – Pointy 2015-03-30 22:12:48
为什么*不会“工作”?它正在完成那个请求。 – user2864740 2015-03-30 22:15:04
在js引擎抛出与不存在的函数相关的错误之前调用'foo()'。 – 2015-03-30 22:16:25