EDIT Oct 2016: Please note this question was asked in 2012. Every month or so someone adds a new answer or comment that refutes an answer, but doesn't really make sense to do so as the question is probably out of date (remember, it was for Gnome Javascript to write gnome-shell extensions, not browser stuff, which is quite specific).
Following my previous question on how to do subclassing in Javascript, I'm making a subclass of a superclass like so:
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.
My question is, how do I define a setter/getter on the prototype with this syntax?
I used to do:
Subclass.prototype = { __proto__: Superclass.prototype, /* other methods here ... */ get myProperty() { // code. } }
But obviously the following won't work:
Subclass.prototype.get myProperty() { /* code */ }
I'm using GJS (GNOME Javascript), and the engine is meant to be the more-or-less same as the Mozilla Spidermonkey one. My code is not intended for a browser so as long as it's supported by GJS (I guess that means Spidermonkey?), I don't mind if it's not cross-compatible.
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
The constructors are used to initialize the instance variable of a class or, create objects. The setter/getter methods are used to assign/change and retrieve values of the instance variables of a class.
__proto__ is a way to inherit properties from an object in JavaScript. __proto__ a property of Object. prototype is an accessor property that exposes the [[Prototype]] of the object through which it is accessed. POSTly is a web-based API tool that allows for fast testing of your APIs (REST, GraphQL).
Getter blocks are expressions that get the current value of the property. Setter blocks are commands that change the value associated with the property.
Use Object.defineProperty()
on Subclass.prototype
. There are also __defineGetter__
and __defineSetter__
available on some browsers, but they are deprecated. For your example, it would be:
Object.defineProperty(Subclass.prototype, "myProperty", { get: function myProperty() { // code } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With