0

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.

Kayrag
  • 19
  • 3

3 Answers3

0

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);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

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.

Udo E.
  • 2,665
  • 2
  • 21
  • 33
0

That is possible with objects such as Number :

var a = new Number(42)

a.value = 43

console.log( a.value )
Slai
  • 22,144
  • 5
  • 45
  • 53