简体   繁体   English

用new实例化对象时,Javascript调用一次构造函数

[英]Javascript invoke constructor function once when object instantiated with new

I am instantiating an object in javascript using a constructor. 我正在使用构造函数在javascript中实例化对象。 Like so: 像这样:

var Constructor = function(){
    this.property1 = "1";    
}
var child = new Constructor();
console.log(child) // Constructor {property1: "1"}

I would like a method to be invoked once whenever a child object is instantiated via the new keyword. 我想只要调用一次的方法child对象通过实例化new关键字。 I would like this method to only be available to the Constructor . 我希望此方法仅对Constructor可用。

This is what I have come up with so far: 到目前为止,这是我想出的:

var Constructor = function(property2){
    this.property1 = "1";
    (function(){ this.property2 = property2}).call(this);
}
var child = new Constructor("2")
console.log(child) // Constructor {property1: "1", property2: "2"}

Is this the correct way to approach this problem in Javascript? 这是解决Javascript中此问题的正确方法吗? Is there a cleaner or more robust way that I could approach this problem? 有没有更清洁或更可靠的方法可以解决此问题?

What you are doing seems kind of useless because you could directly use 您正在做的事情似乎没有用,因为您可以直接使用

var Constructor = function(property2) {
  this.property1 = "1";
  this.property2 = property2;
};

But if your constructor does complex things and what you want is splitting them into parts for better abstraction, then personally I would take these parts outside in order to have a cleaner constructor: 但是,如果您的构造函数做了复杂的事情,并且您想要将它们拆分为更好的抽象部分,那么我个人将这些部分带到外面以拥有一个更简洁的构造函数:

var Constructor = (function() {
  function someLogic(instance, value) {
    instance.property2 = value;
  }
  return function Constructor(property2) {
    this.property1 = "1";
    someLogic(this, property2);
  };
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript构造函数实例化的对象前缀约定 - JavaScript Constructor Function Instantiated Object Prefix Convention 实例化 class 时如何调用 function - How to invoke a function when a class is instantiated 一旦用Javascript实例化,更新API对象就麻烦 - Trouble updating API object once instantiated in Javascript javascript新的对象构造函数替代正确吗? - javascript new object constructor function alternative proper? javascript / typescript 中的构造函数 function 和新 object - constructor function and new object in javascript / typescript 由new构造函数创建的函数对象是否在javascript中被视为可变对象? - Is function object created by `new` constructor treated as mutable object in javascript? 从JavaScript构造函数返回一个对象(避免使用“ new”)时,如何实现公共成员? - When returning an object from a JavaScript constructor function (avoiding 'new') how do I implement public members? 使用构造函数创建新对象并在javascript中调用函数 - Making a new object using a constructor function and calling a function in javascript 在另一个JavaScript函数中获取实例化对象 - Getting instantiated object in another JavaScript function 将构造函数对象传递给自调用函数 - pass constructor object into self invoke function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM