I know how to use JS getters and setters for object properties like so
var myObject = {
value : 0,
get property() {
return this.value;
},
set property(v) {
this.value = v;
}
}
so that calling myObject.property = 2
will set myObject.value
, but what I'm wondering is if there is some way to call myObject = 2
and still set myObject.value
rather than changing myObject
from an object into a number.
It's probably not possible, but javascript is an incredibly flexible language and I thought I'd pose the question to the community before I discarded the idea.
The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.
hasOwnProperty() method Every JavaScript object has a special method object. hasOwnProperty('myProp') that returns a boolean indicating whether object has a property myProp . hero. hasOwnProperty('name') returns true because the property name exists in the object hero .
A function that is a property of an object is called its method. So, here we've got a method sayHi of the object user . Of course, we could use a pre-declared function as a method, like this: let user = { // ... }; // first, declare function sayHi() { alert("Hello!"); } // then add as a method user.
It is possible indeed. Only for global variables though.
Object.defineProperties(this, {
myObject: {
get: function () {
return myObjectValue;
},
set: function (value) {
myObjectValue = value;
},
enumerable: true,
configurable: true
},
myObjectValue: {
value: 0,
enumerable: false,
configurable: true,
writable: true
}
});
myObject = 5;
console.log(myObject);
console.log(delete myObject);
Now, every time you assign a value to myObject
, it shall actually run the set
function and assign the value to the other property instead. Now, if you wanted to minimize pollution, you could create an IIFE and use variables inside that instead to hold the values, per se.
http://jsbin.com/zopefuvi/1/edit
And here is the version with the IIFE.
http://jsbin.com/puzopawa/1/edit
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