如果希望对象中的属性不可更改,可以利用Object.defineProperty 来做。 demo如下:
function Person() { } var feature = { "age" : 10, "sex" : "man" }; var featureConf = {}; featureConf.get = function () { return feature; }; featureConf.set = function () { console.log("can not set feature, but can set feature field"); }; Object.defineProperty(Person, "feature", featureConf); console.log("age is: " + Person.feature.age); Person.feature = {}; // Person.feature.age = 20; // console.log("age after is: " + Person.feature.age);
打印如下: age is: 10
can not set feature, but can set feature field
从打印我们看出Person.feature = {}; 是不行的。
但我们可以修改feature里面的属性。