简体   繁体   English

如何在对象实例中使用构造函数的私有方法

[英]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.

相关问题 如何使用对象作为构造函数? - How to use object as an constructor? 如何在JavaScript中使用继承与构造方法返回具有私有属性的对象文字? - How to Use Inheritance in JavaScript with Constructor Methods Returning Object Literals with Private Properties? 如何为(构造函数,实例)方法编写typescript定义 - How to write typescript definition for is(constructor, instance) method 如果我在构造函数中使用for循环,则私有变量不是特定于对象的:JavaScript - private variable are not object specific if i use for loop in constructor : JavaScript 如何在不使用JavaScript ES6中的构造函数的情况下使用对象文字来创建类的实例? - How can I use an object literal to make an instance of a class without useing the constructor in JavaScript ES6? 从构造函数初始化单个实例,并将其用作另一个类中的静态方法 - Initiate single instance from a constructor and use it as static method in another class 如何在构造函数的方法内部使用方法? - how to use method inside method of a constructor? 如何通过构造函数内部的点符号调用私有方法? - How to call a private method via dot notation inside constructor? 动态将属性附加到构造函数并在新对象实例中使用? - Dynamic attaching property to constructor and use in new object instance? TypeScript:在构造函数中使用private或public - TypeScript: use private or public in constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM