gpt4 book ai didi

javascript - 如何使用链接函数和默认函数正确返回

转载 作者:行者123 更新时间:2023-12-02 16:24:08 25 4
gpt4 key购买 nike

我通过搜索看到的教程会给我留下不想要的格式,例如

main.default('word');
main.default('word').chain();

我想做的事

main('word');
main('word').chain();

This code is just for a console.log() example to see if I can carry the word through. log 'word' or log 'chained word'

如果我返回这个;那么我可以链接:

var main = function(input){

this.input = input;

this.chain = function(){
this.chained='chained '+this.input;
return this.chained;
}

this.default = function(){
return this.input;
}

return this;
};

console.log(main('word').chain()); //'chained word'

但是,我不能这样做 console.log(main('word').chain().chain()); 我认为根据我所读到的内容,因为链式函数不返回 this,而不是返回 this.chained

然后,如果我在 main 函数内 return this.default();,我希望 main 执行的默认操作就会发生

var main = function(input) {


this.input = input;


this.chain = function() {
this.chained = 'out '+this.input;
return this.chained;
}

this.default = function() {
return this.input;
}

return this.default();
};

console.log(main('word')); //'word'

我也一直在查看 jquerys 核心文件,看看我是否可以找出他们是如何使用 jQuery 函数做到这一点的,但我真的看不到那里发生了什么。

最佳答案

这是您要存档的内容吗:

main('word').chain().chain().chain().getInput();
// resulting in 'chained chained chained word'

尝试始终返回this,而不是问题代码中的字符串。现在您可以修改内部变量,但需要一个 get...() 函数从外部访问它们。

var main = function(input) {

this.input = input;

this.chain = function() {
this.input = 'chained ' + this.input;
return this;
}

this.getInput = function() {
return this.input;
}

return this;
};

var valueString = main('word').chain().chain().chain().getInput(); //'chained chained chained word'
document.querySelector('#result').value = valueString;
input {
width: 100%
}
result:
<input id="result" />

关于javascript - 如何使用链接函数和默认函数正确返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28856285/

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