How to define setter/getter on prototype

ぐ巨炮叔叔 提交于 2019-11-26 14:19:39

Using an object literal declaration (simplest way):

var o = {
    a: 7,
    get b() {
        return this.a + 1;
    },
    set c(x) {
        this.a = x / 2
    }
};

Using Object.defineProperty (on modern browsers that support ES5):

Object.defineProperty(o, "myProperty", {
    get: function myProperty() {
        // code
    }
});

Or using __defineGetter__ and __defineSetter__ (DEPRECATED):

var d = Date.prototype;
d.__defineGetter__("year", function() { return this.getFullYear(); });
d.__defineSetter__("year", function(y) { this.setFullYear(y); });
Bergi

Use Object.defineProperty() on Subclass.prototype. There are also __defineGetter__ and __defineSetter__ available on some browsers, but they are deprecated. For your example, it would be:

Object.defineProperty(Subclass.prototype, "myProperty", {
    get: function myProperty() {
        // code
    }
});

I think you wanted to do this way:

function Unit() {
   	this._data; // just temp value
}
Unit.prototype = {
 	get accreation() {
   		return this._data;
   	},
   	set accreation(value) {
   		this._data = value
   	},
}
Unit.prototype.edit = function(data) {
   	this.accreation = data; // setting
   	this.out();
};

Unit.prototype.out = function() {
    alert(this.accreation); // getting
};

var unit = new Unit();
unit.edit('setting and getting');

function Field() {
    // children
}

Field.prototype = Object.create(Unit.prototype);

Field.prototype.add = function(data) {
  this.accreation = data; // setting
   	this.out();
}

var field1 = new Field();
field1.add('new value for getter&setter');

var field2 = new Field();
field2.out();// because field2 object has no setting

To define setters and getters "inside the object's prototype" you have to do something like this:

Object.defineProperties(obj.__proto__, {"property_name": {get: getfn, set: setfn}})

You can short that down with an utility function:

//creates get/set properties inside an object's proto
function prop (propname, getfn, setfn) {
    var obj = {};
    obj[propname] = { get: getfn, set: setfn };
    Object.defineProperties(this, obj);        
}

function Product () {
     this.name =  "Product";
     this.amount =  10;
     this.price =  1;
     this.discount =  0;
}

//how to use prop function
prop.apply(Product.prototype, ["total", function(){ return this.amount * this.price}]);

pr = new Product();
console.log(pr.total);

Here we use prop.apply to set the context Product.prototype as "this" when we call it.

With this code you end with a get/set property inside the object's prototype, not the instance, as the question asked.

(Tested Firefox 42, Chrome 45)

Specify a getter or a setter in constructors by Object.defineProperty() method. This method takes three arguments: the first argument is the object to add the property to, the second is the name of the property, and the third is the property's descriptor. For instance, we can define the constructor for our person object as follows:

var Employee = (function() {
    function EmployeeConstructor() {
        this.first = "";
        this.last = "";
        Object.defineProperty(
            this,
            "fullName", {
                get: function() {
                    return this.first + " " +
                        this.last;
                },
                set: function(value) {
                    var parts = value.toString().split(" ");
                    this.name = parts[0] || "";
                    this.last = parts[1] || "";
                }
            });
    }
    return
    EmployeeConstructor;
}());

Using Object.defineProperty() gives more control over our property definition. For example, we can specify if the property we are describing can be dynamically deleted or redefined, if its value can be changed, and so on.

We can such constraints by setting the following properties of the descriptor object:

  • writable: This is a Boolean that says whether the value of the property can be changed; its default value is false
  • configurable: This is a Boolean that says whether the property's descriptor can be changed or the property itself can be deleted; its default value is false
  • enumerable: This is a Boolean indicating whether the property can be accessed in a loop over the object's properties; its default value is false
  • value: This represents the value associated to the property; its default value is undefined
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!