JavaScript实例函数与原型函数 [英] JavaScript instance functions versus prototype functions
本文介绍了JavaScript实例函数与原型函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
在Javascript中使用'原型'与'这个'?
我对不同类型的JavaScript函数的理解如下:
My understanding of the different kinds of JavaScript functions are as follows:
function MyObj() {
this.propOne = true;
this.publicInstanceFunc = function() {
if (propOne)
return 'public instance function';
}
function privateFunc() {
return 'private function only visible inside this constructor';
}
}
MyObj.prototype.protoFunc = function() {
if (this.propOne)
return 'prototype function shared amongst all instances of MyObj';
}
- 这些是正确的吗?
- 在什么情况下应该在原型上放置函数(例如
protoFunc
)而不是构造函数(例如publicInstanceFunc
)? - 使用
这个
访问原型函数中的属性的正确方法是什么?
- Are these correct?
- In what cases should one put functions on the prototype (e.g.
protoFunc
) vs. in the constructor (e.g.publicInstanceFunc
)? - Is using
this
the correct way to access properties inside prototype functions?
推荐答案
您可以通过将整个事物包装在自动执行的函数中来实际添加另一级别的权限:
You can actually add another level of privilege via wrapping the whole thing in a self-executing function:
var MyObj = (function() { // scoping
var privateSharedVar = 'foo';
function privateSharedFunction() {
// has access to privateSharedVar
// may also access publicSharedVar via explicit MyObj.prototype
// can't be called via this
}
function MyObj() { // constructor
var privateInstanceVar = 'bar';
this.publicInstanceVar = 'baz';
function privateInstanceFunction() {
// has access to all vars
// can't be called via this
};
this.publicInstanceMethod = function() {
// has access to all vars
// also known as a privileged method
};
}
MyObj.prototype.publicSharedVar = 'quux';
MyObj.prototype.publicSharedMethod = function() {
// has access to shared and public vars
// canonical way for method creation:
// try to use this as much as possible
};
return MyObj;
})();
只有'公共'物业可以从外面通过来访问
。
Only 'public' properties can be accessed from outside via this
.
出于性能原因,你应该避免我称之为实例的方法:对于每一种方法,必须为每个方法创建一个新的函数对象 MyObject
实例,而每个'shared'方法只有一个函数对象。
For performance reasons, you should avoid what I called 'instance' methods: For each of these, a new function object must be created for each MyObject
instance, whereas there's only a single function object per 'shared' method.
这篇关于JavaScript实例函数与原型函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文