JavaScript 实例函数与原型函数 [英] JavaScript instance functions versus prototype functions
本文介绍了JavaScript 实例函数与原型函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
在Javascript中使用'prototype'还是'this'?
我对不同种类的 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
)? - 使用
this
是访问原型函数内属性的正确方法吗?
- 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;
})();
只有公共"属性可以通过this
从外部访问.
Only 'public' properties can be accessed from outside via this
.
出于性能原因,您应该避免使用我所说的实例"方法:对于其中的每一个,必须为每个 MyObject
实例创建一个新的函数对象,而每个实例只有一个函数对象共享"方法.
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屋!
查看全文