确保“这个”的最佳做法是什么? Javascript中的上下文? [英] What is a best practice for ensuring "this" context in Javascript?

查看:72
本文介绍了确保“这个”的最佳做法是什么? Javascript中的上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一个简单的Javascript类示例,其中包含公共和私有方法(小提琴: http://jsfiddle.net / gY4mh / )。

Here's a sample of a simple Javascript class with a public and private method (fiddle: http://jsfiddle.net/gY4mh/).

function Example() {
    function privateFunction() {
       // "this" is window when called.
       console.log(this);
    }

    this.publicFunction = function() {
       privateFunction();
    }
}

ex = new Example;
ex.publicFunction();

从公共场所调用私有函数会导致this成为窗口对象。我应该如何确保使用类上下文而不是窗口调用我的私有方法?这是不可取的吗?

Calling the private function from the public one results in "this" being the window object. How should I ensure my private methods are called with the class context and not window? Would this be undesirable?

推荐答案

使用闭包。基本上在函数中声明的任何变量仍然可用于该函数内的函数:

Using closure. Basically any variable declared in function, remains available to functions inside that function :

var Example = (function() {
    function Example() {
        var self = this; // variable in function Example
        function privateFunction() {                  
            // The variable self is available to this function even after Example returns. 
            console.log(self);
        }

        self.publicFunction = function() {
            privateFunction();
        }
    }

    return Example;
})();

ex = new Example;
ex.publicFunction();

这篇关于确保“这个”的最佳做法是什么? Javascript中的上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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