javascript - 确定 JavaScript 函数是否为绑定(bind)函数

标签 javascript function

有没有办法确定 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/

相关文章:

c - 缓冲区溢出或其他

Python 从属性移动到他的类

C++::Template 函数 - 从 object.function 获取对象的地址

c++ - 为什么我的程序有时只能正确识别数组中的最高值和最低值?

javascript - 如何在 anchor 标记内创建下一篇/上一篇文章链接?

javascript - Canvas 上的对 Angular 线以不同的颜色/不透明度绘制

javascript - 如何在 JavaScript 中将选项附加到 optgroup?

c++ - 在函数 C++ 之间传递结构

javascript - 如何为 iPad 拆分 Jquery Mobile 布局?

javascript - 我如何在 typescript/javascript 中将字符串转换为表情符号