javascript - Javascript 中 consice 方法中的词法 this

标签 javascript node.js this

下面是我的代码和解释。 我有一个类,其成员函数和变量如下。 functionOne & functionTwo 是简洁的方法。

function MyUtils() {
    this.actions = {
        functionOne(param1, param2) {
            console.log('This is first function which is not in action');
        },
        functionTwo(param1, param2) {
            console.log('This is second function calling function three');
            //HOW DO I CALL functionThree HERE?
            // I tried doing - this.functionThree() but not working
        }
    }

    this.functionThree() {
        console.log('This is third function');
    }
}

如果函数二被调用,那么我希望函数三在其中被调用?

最佳答案

你可以不用这个关键字,这在 javascript 中使用了闭包语法:

function MyUtils() {

    function functionThree() {
        console.log('This is third function');
    }

    this.actions = {
        functionOne(param1, param2) {
            console.log('This is first function which is not in action');
        },
        functionTwo(param1, param2) {
            console.log('This is second function calling function three');
            //HOW DO I CALL functionThree HERE?
            // I tried doing - this.functionThree() but not working
            functionThree();

        }
    }


}

这是 repl 的输出:(找到 here)

clear
Native Browser JavaScript

This is second function calling function three
This is third function
=> undefined

关于javascript - Javascript 中 consice 方法中的词法 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44673050/

相关文章:

javascript - 在原型(prototype)中保留 'this' 上下文

功能组件无法访问 native 手势处理程序可滑动方法

node.js - 使用 Node js 编写的服务器端脚本如何安全和隐藏?

javascript - 如何在回调中访问正确的“this”?

javascript - meta viewport 标签在 window phone IE 浏览器中不起作用

javascript - Web 服务器上的 html 页面的 XMLHttpRequest 但不在开发中

javascript - 使用信息窗口点击时的 Google Maps API v3 标记

javascript - 根据页面的哪一部分可见,如何在网页上设置 float /固定元素?

javascript - 如何以编程方式触发 Chowkidar 事件

node.js - 是否可以等到ask方法返回响应