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