就像你们都知道一个按钮是一个按钮......点击,向上,向下,这样做,做到这一点。 所以我写了一些默认按钮行为“class / object”。
外部默认button.js:
function Button(parent) {
var self = this;
this.enabled = true;
this.visible = true;
...
this.initialized = false;
f_createButton(parent, self);
this.initialized = true;
...
}
Button.prototype = {
get initialized () {
return this._initialized;
},
set initialized(bool){
this._initialized = bool
if(this.initialized === true) {
... do default stuff
}
},
get enabled(){
return this._enabled;
},
set enabled(bool){
this._enabled = bool;
if(document.getElementById(this.id)) { // is button defined?
var mClassName = document.getElementById(this.id).children[0].className;
document.getElementById(this.id).className = (this.enabled === false) ? "button button-Gray_disabled" : "button button-" + this.defaultStyle;
document.getElementById(this.id).children[0].className = (this.enabled === false) ? mClassName + "_disabled" : mClassName.replace("_disabled","");
}
}
}
function f_createButton("", obj) {
.... create DOM element
}
在html&中包含button.js按钮“类/对象”:
Object.defineProperty(Button.prototype,"buttonStyle", {
get : function() {
return this._buttonStyle;
},
set : function(str) {
this._buttonStyle = str;
if(this.id !== "undefined" && document.getElementById(this.id)) { // is button defined?
document.getElementById(this.id).style.backgroundImage = 'url(Images/'+this.buttonStyle+'/buttons.png)';
}
}
});
这几乎可以工作,但它会杀死原始的Button初始化。
Object.defineProperty(Button.prototype,"initialized", {
set : function( bool ) {
this._initialized = bool;
if(this.initialized === true) {
this.buttonStyle = "NONE";
}
}
});
如何扩展原始的setter?
答案 0 :(得分:0)
你问的问题似乎不寻常,但我们试试吧。首先,考虑一下这个基类,它将在你的外部js文件中:
// Constructor
function Button() {
var self = this;
var _initialized = false; // 'private' property manipulated by the accessors
this.initialized = false;
this.createButton();
this.initialized = true;
}
// Default prototype
Button.prototype = {
createButton: function() {
console.log(' create DOM element ');
}
}
// Default getter/setter on prototype
Object.defineProperty(Button.prototype,"initialized", {
set : function( bool ) {
console.log('this is the original setter');
this._initialized = bool;
if(this._initialized === true) {
console.log('do default stuff')
}
},
get : function() {
return this._initialized;
},
configurable : true // IMPORTANT: this will allow us to redefine it
});
如果我理解你的要求,你想要重新定义initialized
访问者(getter / setter),但仍然可以参考旧的访问者。也许有更好的方法可以做到这一点,但您可以将原始访问者复制到新的访问者中,然后重新定义它:
// Keep reference to the old accessors
var original = Object.getOwnPropertyDescriptor(Button.prototype, 'initialized');
Object.defineProperty(Button.prototype, "oldInitialized", {
set : original.set,
get : original.get
});
// Redefine getter and setter
Object.defineProperty(Button.prototype, "initialized", {
set : function( bool ) {
console.log('this is the new setter');
this.oldInitialized = bool;
},
get : function() {
return this._initialized;
}
});
以下是此代码:http://jsfiddle.net/aTYh3/。