有没有办法确定 JavaScript 函数是否是bound function ?
示例:
var obj = {
x:1
};
function printX() {
document.write(this.x);
}
function takesACallback(cb) {
// how can one determine if this is a bounded function
// not just a function?
if (typeof cb === 'function') {
cb();
}
}
takesACallback(printX.bind(obj)); // 1
takesACallback(printX); // undefined
也许这是很重要的一点。我不是在问为什么第二次调用打印出未定义。
最佳答案
绑定(bind)函数和箭头函数都没有 prototype
属性:
typeof (function() {}).prototype // 'object' as usual
typeof (function() {}).bind(null).prototype // 'undefined'!
typeof (() => {}).prototype // 'undefined'!
这并不是 100% 安全,因为您仍然可以手动分配此属性(尽管这很奇怪)。
因此,检查可绑定(bind)性的简单方法如下:
// ES5
function isBindable(func) {
return func.hasOwnProperty('prototype');
}
// ES6
const isBindable = func => func.hasOwnProperty('prototype');
用法:
isBindable(function () {}); // true
isBindable(() => {}); // false
isBindable(
(function () {}).bind(null)
); // false
这样您就可以确保已传递的函数可以处理动态 this
。
以下是上述方法失败的示例用法:
const arrowFunc = () => {};
arrowFunc.prototype = 42;
isBindable(arrowFunc); // true :(
<小时/>
有趣的是,虽然绑定(bind)函数没有 prototype
属性,但它们仍然可以用作构造函数(使用 new
):
var Animal = function(name) {
this.name = name;
};
Animal.prototype.getName = function() {
return this.name;
};
var squirrel = new Animal('squirrel');
console.log(squirrel.getName()); // prints "squirrel"
var MutatedAnimal = Animal.bind({}); // Radiation :)
console.log(MutatedAnimal.hasOwnProperty('prototype')); // prints "false"
var mutatedSquirrel = new MutatedAnimal('squirrel with two heads');
console.log(mutatedSquirrel.getName()); // prints "squirrel with two heads"
在这种情况下,将使用原始函数 prototype
(Animal
)。
请参阅JS Bin ,代码和链接由 Dmitri Pavlutin 提供.
这当然不适用于箭头函数,因为它们不能用作构造函数。
不幸的是,我不知道是否有一种方法可以区分绑定(bind)函数(可用作构造函数)和箭头函数(不可用作构造函数),而无需尝试
使用new
并检查它是否抛出(new (() => {})
抛出“不是构造函数” 错误)。
关于javascript - 确定 JavaScript 函数是否为绑定(bind)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35686850/