[英]Javascript library template
Let say that i need to create a javascript library like so: 假设我需要像这样创建一个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));
If doSome method work the value of the _ object, and doSome2 and doSome3 too. 如果doSome方法起作用了_对象的值,则doSome2和doSome3也起作用。
But what about chaining the methods like so: 但是如何像这样链接方法:
// 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);
note: methods can be chained randomly, like: 注意:方法可以随机链接,例如:
_.doSome2(value).doSome().doSome3();
Live example: https://jsbin.com/vijehotora/edit?js,console 实时示例: https : //jsbin.com/vijehotora/edit?js,console
You could do something like this: 您可以执行以下操作:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.