gpt4 book ai didi

javascript - 如何在 Javascript 对象构造期间调用函数?

转载 作者:可可西里 更新时间:2023-11-01 02:18:17 26 4
gpt4 key购买 nike

我想创建一个对象并在对象创建时运行它的两个方法。所以如果我的对象是

function newObj(){
this.v1 = 10;
this.v2 = 20;
this.func1 = function(){ ....};
this.func2 = function(){...};
}

对对象的调用是

var temp = new newObj();

我想运行 func1()func2() 而不是在临时变量上显式调用它们,例如 temp.func1()。我希望在创建新的 Object 变量时调用它们。我尝试将 this.func1() 放在 newObj 声明中,但它似乎不起作用。

最佳答案

在构造函数中添加方法调用语句:

function newObj(){this.v1 = 10;this.v2 = 20;this.func1 = function(){ ....};this.func2 = function(){...};this.func1();this.func2();}

我认为这是您需求的解决方案。

关于javascript - 如何在 Javascript 对象构造期间调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4791037/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com