i found 2 define for property in OOP javascript ,which is correct?
- define property inner current object with private field(with var)
- define property in prototype object with public field(with this)
i think first is more like to c# property?
function Pet() {
this._age = 0; //second public feild
_name = 'm2'; //first private feild
this.get_name= function () { //first define
return _name;
}
set_name= function (value) {
this._name = value;
}
}
Pet.prototype = {
speak: function () {
throw Error.notImplemented();
开发者_如何学Go },
get_age: function () { //second define
return this._age;
},
set_age: function (value) {
if (isNaN(value) || value < 0) {
throw Error.argument('age');
}
this._age = 0;
}
}
Pet.registerClass('Pet');
var pet = new Pet();
var u = d.get_name();
first option with var as local vaariable and two getter and setter defines better as property because it give option to control input validation and do custom code when setting value like raiseing event.
With this keyword, it is again works property but is more like public field.
精彩评论