【问题标题】:JavaScript - error this.first() is not a function [duplicate]JavaScript - 错误 this.first() 不是函数 [重复]
【发布时间】:2018-06-22 18:11:11
【问题描述】:

我只是在玩弄并试图弄清楚 this 对象是如何工作的,以及如何使用 bind 函数传递范围上下文。
到目前为止,我已经到了这一点(检查下面的代码),并发现我可以将绑定与对象函数一起使用,以便将 myObject 的范围传递给对象函数 run强>。

第一个问题:

为什么我需要使用 this.first() 而不是 first()?

因为否则它仍然使用 second's 上下文。

    myObject = {
    first: function(){ console.log("myObject's first()")},
    second: function(){ 
        function first(){ console.log("second's first()")};
        let run = function(){ this.first()}.bind(this);
        run();

    },
}

myObject.second()

接下来,我想把它提升到一个新的水平,我在 second 中嵌套了另一个函数(检查代码)。 第二个问题:

从下面的代码中我得到错误 错误:this.first is not a 函数,以及我是否调用 .bind(this) 会给出 同样的错误,任何线索为什么会发生这种情况?

myObject = {
    first: function(){ console.log("myObject's first()")},
    second: function(){ 
        function first(){ console.log("second's first()")};
        function secondx2(){
            function first(){ console.log("secondx2's first()")};
            let run = function(){ this.first()}
            run();
        }
        secondx2();
    },
}

myObject.second()

【问题讨论】:

  • this 和变量范围几乎没有关系。 Function#bind 返回一个新函数,该函数使用特定的 this 值调用其目标函数,但完全不影响作用域,例如 callapply
  • 你打电话给secondx2(),但没有提供this。做secondx2.call(this); 注意:考虑使用箭头函数,它使用词法 this 的方式可能更适合你的情况。
  • @Ryan ya,但是为什么我不能在第二个 sn-p 中运行 this.first()?
  • @user3676224:由 trincot 的评论和副本解释。

标签: javascript this scopes


【解决方案1】:

考虑使用箭头或尝试将其存储在全局变量中以访问您的函数

myObject = {
    first: function(){ console.log("myObject's first()")},
    second: function(){ 
        var scope = this;
        function first(){ console.log("second's first()")};
        function secondx2(){
            function first(){ console.log("secondx2's first()")};
            let run1 = function(){ scope.first()} //myObject's first()

            let run2 = function(){ first()}//secondx2's first()

            run1();
            run2();
        }
        secondx2();
    },
}

myObject.second()

【讨论】:

    猜你喜欢
    • 2017-04-28
    • 2017-10-18
    • 1970-01-01
    • 2021-12-10
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    相关资源
    最近更新 更多