JavaScript:获取对象的评估属性

时间:2022-08-30 10:15:03

I have two objects similar to this:

我有两个与此类似的对象:

var person = {
    fname: 'John',
    lname: 'Doe'
};

var myObj = {
    fullName: function () {
        return person.fname + ' ' + person.lname; 
    }
};

What I need is an object like this – myObj, but evaluated:

我需要的是像这样的对象 - myObj,但是评估了:

var someObj = {
    fullName: 'John Doe'
};

Since myObj will be passed to a templating engine, it's required as JSON anyway, so I found a way using JSON.stringify:

由于myObj将被传递给模板引擎,无论如何都需要它作为JSON,所以我找到了一种使用JSON.stringify的方法:

function replacer(key, value) {
    if (typeof value == 'function') {
        return value.call();
    }
    return value;
}

var someObj = JSON.stringify(myObj, replacer);

While this works, I feel that it's quite brittle and I would like to do some research on it. Is there a special name for functions like replacer, are there any libraries that come with a more mature implementation of replacer?

虽然这有效,但我觉得它非常脆弱,我想对它做一些研究。是否有像replacer这样的函数的特殊名称,是否有任何库具有更成熟的替换器实现?

1 个解决方案

#1


2  

You can make fullName a "getter" property using the proper syntax in the object literal.

您可以使用对象文字中的正确语法使fullName成为“getter”属性。

var person = {
    fname: 'John',
    lname: 'Doe',

    // fullName will be evaluated on property access
    get fullName() {
        return this.fname + ' ' + this.lname; 
    }
};


document.querySelector("pre").textContent = JSON.stringify(person, null, 4);
<pre></pre>

This is an ECMAScript 5 feature, so it will not be available in old browsers, like IE8 and lower.

这是ECMAScript 5的一项功能,因此在IE8及更低版本的旧浏览器中无法使用。

#1


2  

You can make fullName a "getter" property using the proper syntax in the object literal.

您可以使用对象文字中的正确语法使fullName成为“getter”属性。

var person = {
    fname: 'John',
    lname: 'Doe',

    // fullName will be evaluated on property access
    get fullName() {
        return this.fname + ' ' + this.lname; 
    }
};


document.querySelector("pre").textContent = JSON.stringify(person, null, 4);
<pre></pre>

This is an ECMAScript 5 feature, so it will not be available in old browsers, like IE8 and lower.

这是ECMAScript 5的一项功能,因此在IE8及更低版本的旧浏览器中无法使用。