gpt4 book ai didi

javascript - 如果不使用返回值调用方法

转载 作者:行者123 更新时间:2023-11-30 10:06:18 31 4
gpt4 key购买 nike

这是我想要实现的示例代码

function myObj(){
this.method1 = function() {
console.log('method 1 is called');
}
// if method1 is not called ...
this.default = function() {
console.log('default method is called');
}
return this;
}

myObj(); // call default
myObj().method1(); // call method1

在这段代码中,我希望能够检测是否正在使用 myObj() 返回对象(它有一个 method1 方法)。如果是这种情况(如果我们将 myObj() 链接到其他内容),则执行最后一个链接的方法。如果没有则执行 myObj();

中的默认方法

我采用的一种方法是从 myObj() 返回一个函数并像这样:

myObj()();
myObj().method1()();

我还可以将方法传递给基函数并将其链接到对象中:

myObj();
myObj(method1);

但也许还有另一种方法可以做这样的事情,你有什么想法吗?谢谢,

最佳答案

如果不执行类似于调用结果的示例,就无法在 myObj 中检测到它,如下所示:

function myObj(){
var rv = function() {
snippet.log("default method called");
};
rv.method1 = function() {
snippet.log('method 1 is called');
};
return rv;
}

myObj()(); // call default, note the extra ()
myObj().method1(); // call method1 [*no* extra ()]
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

在评论中我说要求额外的 () 是自找麻烦,因为它很容易忘记,但是当然,如​​果 myObj 本身没有除了返回一个函数之外做任何事情,那么如果您忘记了 (),您将看不到默认功能,并且可能会意识到您忘记了 ()


在其他地方的评论中,您说您可能想要进行链接。你可以用上面的方法做到这一点,只需在函数的末尾添加“return rv”:

function myObj(){
var rv = function() {
snippet.log("default method called");
return rv;
};
rv.method1 = function() {
snippet.log('method 1 is called');
return rv;
};
return rv;
}

myObj()(); // call default, note the extra ()
myObj().method1(); // call method1 [*no* extra ()]
myObj()().method1()(); // call default, then method1, then default
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


我确定您已经排除了这种可能性,但只是为了完整起见:通常的做法是让“默认”明确,例如:

function myObj(){
return {
_: function() {
snippet.log("default method called");
},
method1: function() {
snippet.log('method 1 is called');
}
};
}

myObj()._(); // call default
myObj().method1(); // call method1
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

然后您当然可以使用原型(prototype)链和所有其他标准对象优点。

关于javascript - 如果不使用返回值调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28958155/

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