[英]How to use private method of a constructor in object instance
I have made a constructor function. 我做了一个构造函数。 I am now adding properties and methods to it.
我现在正在添加属性和方法。 Now, I also add a private function named ceta() to it.
现在,我还添加了一个名为ceta()的私有函数。 After, I make an instance (obj1) from constructor function, how can I use private function to object instance (Not, using call, apply, bind).
之后,我从构造函数中创建一个实例(obj1),如何使用私有函数来对象实例(不是,使用call,apply,bind)。
<html> <head></head> <body> <script> function alpha(){ this.a = 10; this.b = 20; this.beta = function(){ this.c = 30; alert (c); } var ceta = function(){ alert ("hi!"); } } var obj1 = new alpha; obj1.beta();// this works obj1.ceta();// this not </script> </body> </html>
ceta
is in the scope of constructor function alpha
but do not belong to the objects being constructed. ceta
在构造函数alpha
的范围内,但不属于正在构造的对象。 It can be used in or taken under closure and returned from this.beta
function though. 它可以在关闭时使用或者在关闭时使用,但是从
this.beta
函数返回。 Such as; 如;
function alpha(){
this.a = 10;
this.b = 20;
this.beta = function(){
ceta(); // <<-- invoke here for some purpose
this.c = 30;
alert(this.c);
return ceta; // <<-- or return here
}
var ceta = function(){
alert ("hi!");
}
}
var obj = new alpha(),
ceta = obj.beta(); // alerts twice and obj.c is set to 30
But these are mostly useless practices. 但这些都是无用的做法。 The main task of
ceta
should be to provide utility services to help the constructor to construct objects. ceta
的主要任务应该是提供实用程序服务来帮助构造函数构造对象。
If you need to access ceta
from all instances of alpha
then put it in the prototype of alpha
. 如果你需要从所有
alpha
实例中访问ceta
,那么将它放在alpha
的原型中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.