从原型定义的函数访问私有成员变量 [英] Accessing private member variables from prototype-defined functions

查看:195
本文介绍了从原型定义的函数访问私有成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法制作私有变量(在构造函数中定义的变量),可用于原型定义的方法?

Is there any way to make "private" variables (those defined in the constructor), available to prototype-defined methods?

TestClass = function(){
    var privateField = "hello";
    this.nonProtoHello = function(){alert(privateField)};
};
TestClass.prototype.prototypeHello = function(){alert(privateField)};

这有效:

t.nonProtoHello()

但这不是:

t.prototypeHello()

我习惯在构造函数中定义我的方法,但由于一些原因我正在远离它。

I’m used to defining my methods inside the constructor, but am moving away from that for a couple reasons.

推荐答案

不,没有办法做到这一点。这基本上是反过来的范围。

No, there's no way to do it. That would essentially be scoping in reverse.

构造函数中定义的方法可以访问私有变量,因为所有函数都可以访问定义它们的作用域。

Methods defined inside the constructor have access to private variables because all functions have access to the scope in which they were defined.

原型上定义的方法没有在构造函数的范围内定义,也无法访问构造函数的局部变量。

Methods defined on a prototype are not defined within the scope of the constructor, and will not have access to the constructor's local variables.

您仍然可以拥有私有变量,但是如果您希望原型上定义的方法可以访问它们,您应该在这个上定义getter和setter。对象,原型方法(以及其他所有内容)可以访问。例如:

You can still have private variables, but if you want methods defined on the prototype to have access to them, you should define getters and setters on the this object, which the prototype methods (along with everything else) will have access to. For example:

function Person(name, secret) {
    // public
    this.name = name;

    // private
    var secret = secret;

    // public methods have access to private members
    this.setSecret = function(s) {
        secret = s;
    }

    this.getSecret = function() {
        return secret;
    }
}

// Must use getters/setters 
Person.prototype.spillSecret = function() { alert(this.getSecret()); };

这篇关于从原型定义的函数访问私有成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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