I using js and i want set property of object properties
var a=42
Object.defineProperty(this,"a",{value:43} )//Error
How I can set property of object properties after defining.
I using js and i want set property of object properties
var a=42
Object.defineProperty(this,"a",{value:43} )//Error
How I can set property of object properties after defining.
Currently, a
is a primitive type (number
). You can just update it how you would any other variable:
var a = 42;
a = 43;
console.log(a);
If you want an object, you have two choices - define a
as an object and change the value
property, or reassign a
to be an object with a value
property.
Method one:
var a = {
value: 42
};
a.value = 43;
console.log(a);
Method 2:
var a = 42;
a = {
value: 43
};
console.log(a);
To extend an object's property in javascript you use the prototype
proterty that is already possessed by Object
.
All javascript objects are instances of Object
and inherit from Object.prototype
. So you can extend the property of this class to add a property to any other objects in javascript like this:
var a = 42;
Object.prototype.getValue = 43;
document.write(a.getValue); // output should be 43.
see the jsfiddle sample here.
That is possible with objects such as Number
:
var a = new Number(42)
a.value = 43
console.log( a.value )