直接在函数声明中使用function.prototype.bind [英] Using function.prototype.bind directly on function declaration

查看:60
本文介绍了直接在函数声明中使用function.prototype.bind的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么允许这样做?

var f = function() {
  console.log(this.x);
}.bind({x:1})();

为什么这不是或更好为什么我在这种情况下会出现语法错误?

And why this is not or better why I get syntax error in this case ?

function f() {
  console.log(this.x);
}.bind({x:1})();

那么,为什么我需要函数表达式语法来完成这项工作,有没有办法直接在函数声明上使用 bind 方法?

So, why I need function expression syntax to get this work and is there a way to use bind method directly on function declaration ?

推荐答案

第二个例子有效,但语法稍微偏离:

The second example works but the syntax is slightly off:

将函数包含在parens中。我不得不说,我不完全确定为什么。似乎没有parens会工作吗? :P

Surround the function in parens. I have to say that I'm not entirely sure why. It seems like it would work without the parens huh? :P

(function f() {
    console.log(this.x);
}).bind({x:1})();

这篇关于直接在函数声明中使用function.prototype.bind的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆