使用Object.DefineProperty并访问私有作用域中的变量 [英] Using Object.DefineProperty and accessing a variable in private scope

查看:177
本文介绍了使用Object.DefineProperty并访问私有作用域中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下不工作,从我的getter,我看不到在'class'Person中定义的 _nickname

The following doesn't work, from my getter, I can't see _nickname defined in the 'class' Person.

var Person = function (args) {

    var _nickname = '';
    if (args === undefined || args === null) {
        return;
    }
    if (args.nickname !== undefined && args.nickname !== null) {
        _nickname = args.nickname;
    }

}

Object.defineProperty(Person.prototype, "nickname", {
    get : function () {
        return _nickname;
    }
});

var x = new Person({
        nickname : 'bob'
    });

console.log(x.nickname);

如何完成这个?
是否有一种方法可以从函数的原型中添加_nickname到原型中?

How should one go about accomplishing this? Is there a way of adding _nickname to the prototype of Person from within its function?

推荐答案


是否有一种方法可以在函数的原型中添加_nickname到原型中?

Is there a way of adding _nickname to the prototype of Person from within its function?

如果你的意思是 Person 构造函数,确定(虽然在我看来它看起来不是很优雅):

If you mean the Person constructor, sure (although in my opinion it doesn't look very elegant):

var Person = function (args) {
    var _nickname = '';
    if (args === undefined || args === null) {
        return;
    }
    if (args.nickname !== undefined && args.nickname !== null) {
        _nickname = args.nickname;
    }
    Object.defineProperty(this, "nickname", {
        get : function () {
            return _nickname;
        }
    });
}

var x = new Person({
    nickname : 'bob'
});

console.log(x.nickname);

http://jsfiddle.net/JEbds/

在这种情况下,您的getter只是另一个闭包,因此它可以访问 _nickname 。它不是在原型,你需要一个自己的属性来完成这一点。

In this case, your getter is just another closure, so it has access to _nickname. And it's not on the prototype anymore, you need an own property to accomplish that.

这篇关于使用Object.DefineProperty并访问私有作用域中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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