gpt4 book ai didi

JavaScript 库模板

转载 作者:行者123 更新时间:2023-12-03 08:37:41 25 4
gpt4 key购买 nike

假设我需要创建一个像这样的 JavaScript 库:

;(function(){

var root = this;

var Ctor = function(value) {
this.value = value;
};

var _ = new Ctor(value);

_.doSome = function(value) {
// do some work to the value
// if no value assigned, get the value of the previous method
};

_.doSome2 = function(value) {
// do some work to the value
// if no value assigned, get the value of the previous method
};

_.doSome3 = function(value) {
// do some work to the value
// if no value assigned, get the value of the previous method
};

root._ = _;

}.call(this));

如果 doSome 方法对 _ 对象的值起作用,那么 doSome2 和 doSome3 也是如此。

但是像这样链接方法怎么样:

// the doSome2 and doSome3 work with the value of doSome
_.doSome(value).doSome2().doSome3();

// the doSome3 work with the value of doSome2 cuz it has a value
_.doSome(value).doSome2(value).doSome3();

// every method work with the value assigned to it
_.doSome(value).doSome2(value).doSome3(value); // the same as:
_.doSome(value);
_.doSome2(value);
_.doSome3(value);

注意:方法可以随机链接,例如:

_.doSome2(value).doSome().doSome3();

实例:https://jsbin.com/vijehotora/edit?js,console

最佳答案

你可以这样做:

var Ctor = function() {};

Ctor.prototype = {
doSome: function(value) {
if(value) {
this.value = value;
}

return this;
},

doSome2: function(value) {
if(value) {
this.value = value;
}

return this;
}
};

new Ctor().doSome('value1').doSome2('value2').doSome();

Working example

关于JavaScript 库模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33147830/

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