Javascript Javascript向对象添加方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13521833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript add method to object
提问by Chin
Suppose I have a Fooobject
假设我有一个Foo对象
How can I extend this object by adding a bar()method and also ensure that future instances of Foohave this method?
我如何通过添加一个bar()方法来扩展这个对象,并确保未来的实例Foo拥有这个方法?
回答by VeXii
you need to add it to Foo's prototype:
您需要将其添加到 Foo 的原型中:
function Foo(){}
Foo.prototype.bar = function(){}
var x = new Foo()
x.bar()
回答by Norguard
This all depends on how you're creating Foo, and how you intend to use .bar().
这一切都取决于您如何创建Foo以及您打算如何使用.bar().
First, are you using a constructor-function for your object?
首先,您是否为您的对象使用构造函数?
var myFoo = new Foo();
If so, then you can extend the Foofunction's prototypeproperty with .bar, like so:
如果是这样,那么您可以使用 扩展Foo函数的prototype属性.bar,如下所示:
function Foo () { /*...*/ }
Foo.prototype.bar = function () { /*...*/ };
var myFoo = new Foo();
myFoo.bar();
In this fashion, each instance of Foonow has access to the SAMEinstance of .bar.
To wit: .barwill have FULL access to this, but will have absolutely no accessto variableswithin the constructor function:
在这种方式下,每个实例Foo现在可以访问SAME的实例.bar。
即:.bar必须完全访问this,但将有绝对没有进入到variables构造函数中:
function Foo () { var secret = 38; this.name = "Bob"; }
Foo.prototype.bar = function () { console.log(secret); };
Foo.prototype.otherFunc = function () { console.log(this.name); };
var myFoo = new Foo();
myFoo.otherFunc(); // "Bob";
myFoo.bar(); // error -- `secret` is undefined...
// ...or a value of `secret` in a higher/global scope
In another way, you could define a function to return any object (not this), with .barcreated as a property of that object:
换句话说,您可以定义一个函数来返回任何对象(不是this),并将其.bar作为该对象的属性创建:
function giveMeObj () {
var private = 42,
privateBar = function () { console.log(private); },
public_interface = {
bar : privateBar
};
return public_interface;
}
var myObj = giveMeObj();
myObj.bar(); // 42
In this fashion, you have a function which creates new objects.
Each of those objects has a .barfunction created for them.
Each .barfunction has access, through what is called closure, to the "private" variables within the function that returned their particular object.
Each .barstill has access to thisas well, as this, when you call the function like myObj.bar();will always refer to myObj(public_interface, in my example Foo).
以这种方式,您有一个创建新对象的函数。
这些对象中的每一个都有一个.bar为它们创建的函数。
每个.bar函数都可以通过所谓的闭包访问返回其特定对象的函数中的“私有”变量。
每个人.bar仍然可以访问thisas this,当您调用函数时, likemyObj.bar();将始终引用myObj( public_interface,在我的示例中Foo)。
The downside to this format is that if you are going to create millions of these objects, that's also millions of copies of .bar, which will eat into memory.
这种格式的缺点是,如果您要创建数百万个这样的对象,那也是数百万个 的副本.bar,这会占用内存。
You could also do this inside of a constructor function, setting this.bar = function () {};inside of the constructor -- again, upside would be closure-access to private variables in the constructor and downside would be increased memory requirements.
您也可以在构造函数内部执行此操作,在构造函数this.bar = function () {};内部进行设置——同样,优点是可以关闭对构造函数中私有变量的访问,缺点是内存需求增加。
So the first question is:
Do you expect your methods to have access to read/modify "private" data, which can't be accessed through the object itself (through thisor myObj.X)?
所以第一个问题是:
您是否希望您的方法能够读取/修改无法通过对象本身(通过this或myObj.X)访问的“私有”数据?
and the second question is: Are you making enough of these objects so that memory is going to be a big concern, if you give them each their own personal function, instead of giving them one to share?
第二个问题是:如果你给它们每个人自己的个人功能,而不是让它们分享,你是否制作了足够多的这些对象,以至于记忆将成为一个大问题?
For example, if you gave every triangle and every texture their own .drawfunction in a high-end 3D game, that might be overkill, and it would likely affect framerate in such a delicate system...
例如,如果您.draw在高端 3D 游戏中为每个三角形和每个纹理赋予自己的功能,那可能就有点矫枉过正了,而且很可能会影响如此精细系统中的帧率……
If, however, you're looking to create 5 scrollbars per page, and you want each one to be able to set its position and keep track of if it's being dragged, without letting every other application have access to read/set those same things, then there's really no reason to be scared that 5 extra functions are going to kill your app, assuming that it might already be 10,000 lines long (or more).
但是,如果您希望为每页创建 5 个滚动条,并且您希望每个滚动条都能够设置其位置并跟踪它是否被拖动,而不让其他所有应用程序都有权读取/设置这些相同的内容,那么真的没有理由害怕 5 个额外的函数会杀死你的应用程序,假设它可能已经有 10,000 行(或更多)。
回答by Oliver Moran
There are many ways to create re-usable objects like this in JavaScript. Mozilla have a nice introduction here:
有很多方法可以在 JavaScript 中创建像这样的可重用对象。Mozilla 在这里有一个很好的介绍:
The following will work in your example:
以下将适用于您的示例:
function Foo(){
this.bar = function (){
alert("Hello World!");
}
}
myFoo = new Foo();
myFoo.bar(); // Hello World?????????????????????????????????
回答by user1832281
You can make bar a function making it a method.
您可以使 bar 成为一个函数,使其成为一个方法。
Foo.bar = function(passvariable){ };
As a property it would just be assigned a string, data type or boolean
作为一个属性,它只会被分配一个字符串、数据类型或布尔值
Foo.bar = "a place";

