在JavaScript中更改对象的类型 [英] Changing an Object's Type in JavaScript

查看:89
本文介绍了在JavaScript中更改对象的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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.

或者如果你不关心IE:

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();

这篇关于在JavaScript中更改对象的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆