如何正确扩展JS对象? [英] How can I extend properly a JS object?

查看:56
本文介绍了如何正确扩展JS对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在名为 main.js 的文件中有类似的内容:

Let's say I have something like this in a file named main.js:

function obj_name() {}

obj_name.prototype = {
    foo  : function() { alert('hi!'); },
    foo2 : function() { alert('hi again!'); }
}

现在我正在尝试这种方式来扩展另一个文件中的对象 extend.js

Now I am trying this way to expand the object in another file extend.js:

obj_name.prototype = {
    newfoo : function() { alert('hi #3'); }
}

...但问题是如果我编码它会起作用这样:

... but the problem is that it will just work if I code it this way:

obj_name.prototype.newfoo = function() { alert('hi #3'); }

我想这可能是一个菜鸟问题。我甚至都不知道这是否是扩展对象的正确方法,但我在这里想知道为什么会发生这种情况。

I guess this may be a noob question. I don't even know if this is the proper way to extend an object, but I am freaking out here wondering why does this happen.

提前谢谢你们。

推荐答案

在第一种方式中,您将用新的原型替换原型(覆盖之前的原型)。在第二种方式中,您将向原型添加一个新成员(从而扩展它)。

In the first way, you are replacing the prototype with a new one (overwriting what was there before). In the second way, you are adding a new member to the prototype (thus expanding it).

还有另一种方法:具有 extend 方法或类似方法(基本上将你在第二种形式中所做的事情包装在一个漂亮的包装器中)。例如,在 jQuery 中:

There is another method: a library that has an extend method or similar (which basically wraps what you're doing in your second form in a nice wrapper). For example, in jQuery:

$.extend(obj_name.prototype, {
    newfoo : function() { alert('hi #3'); }
}

这篇关于如何正确扩展JS对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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