Getter / setter在构造函数中 [英] Getter/setter in constructor

查看:232
本文介绍了Getter / setter在构造函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近读过一个事实,即有可能在JavaScript中定义getter / setter。这似乎是非常有帮助的 - setter是一种帮助器,可以在实际设置之前解析要设置的值。

I recently read about the fact that there is a possibility of defining getters/setters in JavaScript. It seems extremely helpful - the setter is a kind of 'helper' which can parse the value to be set first, before actually setting it.

例如,这个代码:

var obj = function(value) {
    var test = !!value; // 'test' has to be a boolean
    return {
        get test() { return test },
        set test(value) { test = !!value }
    };
};

var instance = new obj(true);

此代码总是将 value 转换为布尔值。因此,如果你编写 instance.test = 0 ,则 instance.test === false

This code always converts value to a boolean. So if you code instance.test = 0, then instance.test === false.

但是,为了这个工作你必须返回一个对象,这意味着新的实例不是 obj 但只是一个简单的对象。这意味着更改 obj 的原型对实例没有影响。例如,工作 - instance.func 未定义:

However, for this to work you have to actually return an object, which means that the new instance is not of type obj but just is a plain object. This means that changing the prototype of obj has no effect on instances. For example, this does not work - instance.func is undefined:

obj.prototype.func = function() { console.log(this.value); };

因为实例不是类型 obj 。为了让原型函数工作,我想我不应该返回一个简单的对象,而是不返回任何东西,所以实例只是类型 obj ,像一个常规的构造函数。

because instance is not of type obj. To get the prototype functions work, I guess I should not return a plain object, but rather not return anything so that instance would just be of type obj, like a regular constructor works.

问题是如何实现getter / setter?我只能找到文章描述如何添加这些到一个对象,而不是作为自定义类型的构造函数的一部分。

The problem then is how to implement getters/setters? I can only find articles describing how to add these to an object, not as being part of the constructor of a custom type.

那么如何实现getters / setters构造函数,以便能够使用getter / setter和扩展原型?

So how do I implement getters/setters in the constructor so as to be able to both use getters/setters and extending the prototype?

推荐答案

你不能这样做。

您可以为对象的属性设置setter / getter。我建议您使用ES5 Object.defineProperties 。当然这只适用于现代浏览器。

You can set setter/getters for properties of objects though. I advice you use ES5 Object.defineProperties though. of course this only works in modern browsers.

var obj = function() {
    ...
    Object.defineProperties(this, {
        "test": {
             "get": function() { ... },
             "set": function() { ... }
        }
    });
}

obj.prototype.func = function() { ... }

var o = new obj;
o.test;
o.func();

这篇关于Getter / setter在构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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