gpt4 book ai didi

javascript - bind() 的奇怪语法问题

转载 作者:行者123 更新时间:2023-11-28 18:49:52 24 4
gpt4 key购买 nike

为什么在这个例子中 myFunction1 抛出语法错误而 myFunction2 运行良好?它们不应该都是一样的吗?

(function(){
function MyClass(){
this.val = "myVal";
this.myFunction1();
this.myFunction2();
}

MyClass.prototype.myFunction1 = function(){
function otherFn() {
console.log(this.val);
}.bind(this);
otherFn();
}

MyClass.prototype.myFunction2 = function(){
var otherFn= function() {
console.log(this.val);
}.bind(this);
otherFn();
}

var ins = new MyClass();
})();

最佳答案

这里的区别是函数声明函数表达式之间的区别。

您的function1使用函数声明:

MyClass.prototype.myFunction1 = function(){
function otherFn() {
console.log(this.val);
}.bind(this);
otherFn();
}

函数声明不是表达式,并且不会在代码的逐步执行中发生。在进入范围后,它们首先完成。

由于它们不是表达式,因此没有值,因此 .bind 无法处理任何内容。

您的第二个示例使用函数表达式:

MyClass.prototype.myFunction2 = function(){
var otherFn= function() {
console.log(this.val);
}.bind(this);
otherFn();
}

由于这是一个表达式,因此它会在代码的逐步执行中进行求值,并产生一个结果值,.bind 可以对其进行操作。

那么为什么第一个是声明呢?纯粹是因为 JavaScript 的解析规则是如何定义的。如果在需要语句时遇到function,则会启动函数声明。如果在需要表达式的地方遇到function,它将启动一个函数表达式。

function1 中,function 出现在需要语句的位置,因此是一个声明。但在 function2 中,它出现在 var otherFn= 之后,因此只能是一个表达式。

<小时/>

(* "where a statement is Expected"在 JavaScript 中,任何表达式[除了函数表达式]都可以在需要语句的地方使用,它被称为 ExpressionStatement。所以它结束up 是“需要语句或非函数表达式的地方。但反之则不然,当需要表达式时,语句无效。”

关于javascript - bind() 的奇怪语法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34653640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com