編輯2016年10月:請注意這個問題在2012年被問到。每個月左右有人添加一個新的答案或評論來駁斥答案,但並沒有真正意義這樣做的問題可能已過時(請記住,它是用於編寫gnome-shell擴展的,而不是瀏覽器的東西,這非常具體),用於Gnome Javascript。如何在原型上定義setter/getter
下面就如何在Javascript中做子類my previous question,我正在做一個超類的子類,像這樣:
function inherits(Child,Parent) {
var Tmp = function {};
Tmp.prototype = Parent.prototype;
Child.prototype = new Tmp();
Child.prototype.constructor = Child;
}
/* Define subclass */
function Subclass() {
Superclass.apply(this,arguments);
/* other initialisation */
}
/* Set up inheritance */
inherits(Subclass,Superclass);
/* Add other methods */
Subclass.prototype.method1 = function ... // and so on.
我的問題是,我怎麼定義的原型,一個setter /吸氣這個語法?
我以前做的:
Subclass.prototype = {
__proto__: Superclass.prototype,
/* other methods here ... */
get myProperty() {
// code.
}
}
但顯然以下將不起作用:
Subclass.prototype.get myProperty() { /* code */ }
我使用GJS(GNOME的Javascript),發動機,就是要與Mozilla Spidermonkey相同或多或少。我的代碼不適用於瀏覽器,只要它支持GJS(我猜這意味着Spidermonkey?),我不介意它是不是交叉兼容的。
Mozilla文檔提到'__defineGetter__'和'__defineSetter'(但我從來沒有真正使用過那些...)。 https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Objects#Defining_getters_and_setters – bfavaretto
非常棒,這看起來像我之後。如果您將它作爲答案發布,我會接受它。乾杯! :) –
做到了這一點,並添加了來自MDN的示例。 – bfavaretto