javascript中的自动getter和setter(带验证) [英] automatic getter and setter(with validation) in javascript

查看:39
本文介绍了javascript中的自动getter和setter(带验证)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 javascript 库,我必须在其中创建类日志,其中大多数都有许多必须向用户公开的属性.

I am building a javascript library where I have to create a log of classes and most of them have a lot of properties which have to make public for the user.

例如:

function Person(name,age){

}

现在我想为属性(名称和年龄)创建 getter 和 setter.

Now I want to create the getter and setter for properties (name and age).

Nornall,我必须将这些方法添加到 Person.prototype 中:

Nornall, I have to add these methods to Person.prototype:

Person.prototype.getName=function(){}
Person.prototype.setName=function(x){
  //check if x is typeof String
}
Person.prototype.getAge=function(){}
Person.prototype.setAge=function(x){
  //check if x is typeof Number
}

这将导致两行多行重复代码.

This will result in two many lines of repeated codes.

所以我想知道我是否可以调用这样的方法:

So I wonder if I can call a method like this:

makeThesePropertiesPublic(Person,{
  name:"string",
  age:"number"
});

然后我可以称之为:

var p=new Person("xx",1);
p.getName();
p.getAge();
.......

是否有现成的方法来实现这一点?

Is there a out-of-box method to implement this?

推荐答案

首先你不能在 prototype 上定义 getter 和 setter 函数,因为它们需要能够访问 nameage 只能在构造函数内部访问.因此,您需要在构造函数中定义 getter 和 setter 函数.

First of all you can't define the getter and setter functions on the prototype because they need to be able to access name and age which are only accessible inside the constructor. Hence you would need to define the getter and setter functions inside the constructor.

我会这样做:

function Person(name, age) {
    var private = {
        name: name,
        age: age
    };

    Object.defineProperties(this, {
        name: getAccessor(private, "name", "String"),
        age: getAccessor(private, "age", "Number")
    });
}

function getAccessor(obj, key, type) {
    return {
        enumerable: true,
        configurable: true,
        get: function () {
            return obj[key];
        },
        set: function (value) {
            if (typeOf(value) === type)
                obj[key] = value;
        }
    };
}

function typeOf(value) {
    return Object.prototype.toString.call(value).slice(8, -1);
}

现在您可以访问创建一个 Person 并访问他们的 nameage 属性,如下所示:

Now you can access create a Person and access their name and age properties as follows:

var person = new Person("Aadit M Shah", 20);

person.name = 0;       // it won't set the name
person.age = "twenty"; // it won't set the age

alert(person.name);
alert(person.age);

查看演示:http://jsfiddle.net/aVM2J/

这篇关于javascript中的自动getter和setter(带验证)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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