在JavaScript中更改对象的类型

Ray*_*Ray 10 javascript javascript-objects

我有一个用JSON定义的现有对象数组.对象显然是Object类型.如何将它们与自定义对象类型相关联以为其提供特定功能?

Jer*_*emy 13

在所有浏览器中工作的方式是使用所需的属性和方法扩充数组中的每个项目,或者将对象传递给构造函数并基于旧对象的属性和方法创建新对象.

或者如果你不关心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();
Run Code Online (Sandbox Code Playgroud)