为了账号安全,请及时绑定邮箱和手机立即绑定

如何在原型上定义setter / getter

如何在原型上定义setter / getter

冉冉说 2019-11-27 10:37:10
请注意,此问题是在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?),我就不在乎它是否不兼容。
查看完整描述

3 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

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


Object.defineProperty(Subclass.prototype, "myProperty", {

    get: function myProperty() {

        // code

    }

});


查看完整回答
反对 回复 2019-11-27
?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

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


查看完整回答
反对 回复 2019-11-27
  • 3 回答
  • 0 关注
  • 435 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号