I have an array of existing object defined with JSON. The objects are obviously of the Object type. How do I associate them with a custom object type to give them specific functionality?
Using the same method, an object's property can be modified by assigning a new value to an existing property. At this point, if we call the object, we will see all of our additions and modifications. Through assignment operation, we can modify the properties and methods of a JavaScript object.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
Setting Properties of Existing Objects After you have created an object, you can set or change its properties by calling the property directly with the dot operator (if the object inherits from IDL_Object) or by calling the object's SetProperty method.
An object type is simply a collection of properties in the form of name and value pairs. Notice from the list that null and undefined are primitive JavaScript data types, each being a data type containing just one value.
The way that'll work in all browsers is to either augment each item in the array with the properties and methods you want, or pass the object to a constructor and create a new object based on the old object's properties and methods.
Or if you don't care about IE:
var obj = {
name : "Jeremy"
};
function CustomType() {
this.name = this.name || "someValue";
this.greeting = "Hi";
}
CustomType.prototype.sayHi = function() {
alert(this.greeting + ", " + this.name);
};
obj.__proto__ = CustomType.prototype;
obj.constructor.call(obj);
obj.sayHi();
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