admin管理员组

文章数量:1356424

I want to convert a data property to accessor property using Object.defineProperty() . Consider the code for this which leads to Uncaught RangeError: Maximum call stack size exceeded error

var c = { name: 'abcde'};
Object.defineProperty(c, 'name', {
    get: function() {
        return this.name; //causes stack overflow
    },
    set: function(x) {
       this.name = x; //causes stack overflow
        }
}); 
c.name="xyz";  
console.log(c.name);

I understood why the error crops in. One of the proposed solution is to remove 'this' from getter and setter and it seems to work.

var c = { name: 'abcde'};
Object.defineProperty(c, 'name', {
    get: function() {
        return name; //removed this
    },
    set: function(x) {
       name = x; //removed this
        }
}); 
c.name="xyz";  
console.log(c.name);

What is happening ? In general , I want to ask how to convert a data property to accessor property using Object.defineProperty() ?

I want to convert a data property to accessor property using Object.defineProperty() . Consider the code for this which leads to Uncaught RangeError: Maximum call stack size exceeded error

var c = { name: 'abcde'};
Object.defineProperty(c, 'name', {
    get: function() {
        return this.name; //causes stack overflow
    },
    set: function(x) {
       this.name = x; //causes stack overflow
        }
}); 
c.name="xyz";  
console.log(c.name);

I understood why the error crops in. One of the proposed solution is to remove 'this' from getter and setter and it seems to work.

var c = { name: 'abcde'};
Object.defineProperty(c, 'name', {
    get: function() {
        return name; //removed this
    },
    set: function(x) {
       name = x; //removed this
        }
}); 
c.name="xyz";  
console.log(c.name);

What is happening ? In general , I want to ask how to convert a data property to accessor property using Object.defineProperty() ?

Share Improve this question edited Jan 23, 2017 at 18:57 Number945 asked Jan 23, 2017 at 10:11 Number945Number945 4,98010 gold badges53 silver badges90 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

The second code doesn't actually work because it uses the global variable called name to store the value, instead of storing it in the object c.

It would be rejected by ES5 "strict mode", if it weren't for the fact that window.name is a default property of the global object in browsers.

A more appropriate fix would be to store the value in a lexically scoped private variable:

var c = (function() {
    var obj = {};
    var name = "abcde";

    Object.defineProperty(obj, "name", {
        get: function() {
            return name;
        },
        set: function(x) {
            name = x;
        }
    });

    return obj;
})();

本文标签: javascriptUsing getter and setter with ObjectdefinePropertyStack Overflow