猿问

如何在原型上定义setter / getter

请注意,此问题是在2012年提出的。每个月左右,有人会添加一个新的答案或评论来驳斥该答案,但这样做实际上没有任何意义,因为该问题可能已过时(请记住,是Gnome Javascript编写gnome-shell扩展,而不是浏览器的东西,这是相当具体的)。


继我先前关于如何在Javascript中进行子类化的问题之后,我正在制作一个超类的子类,如下所示:


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 / getter?


我曾经做:


Subclass.prototype = {

    __proto__: Superclass.prototype,

    /* other methods here ... */


    get myProperty() {

        // code.

    }

}

但是很明显,以下方法不起作用:


Subclass.prototype.get myProperty() { /* code */ }

我使用的是GJS(GNOME Javascript),该引擎与Mozilla Spidermonkey差不多。我的代码不适合浏览器使用,只要它受GJS支持(我想这意味着Spidermonkey?),我就不在乎它是否不兼容。


冉冉说
浏览 436回答 3
3回答

鸿蒙传说

Object.defineProperty()在上使用Subclass.prototype。在某些浏览器中也有__defineGetter__ 并且__defineSetter__可用,但已弃用。以您的示例为例:Object.defineProperty(Subclass.prototype, "myProperty", {    get: function myProperty() {        // code    }});

天涯尽头无女友

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
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答