Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing an Object's Type in JavaScript

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?

like image 994
Ray Avatar asked Jul 02 '10 15:07

Ray


People also ask

Can you modify an object in JavaScript?

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.

How do you convert an object in JavaScript?

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.

How do you change an object property?

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.

What is the object type in JavaScript?

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.


1 Answers

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();
like image 129
Jeremy Avatar answered Oct 09 '22 07:10

Jeremy