다음과 같이 자바 스크립트 라이브러리를 만들어야한다고 가정 해 보겠습니다.
;(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();
다음과 같이 할 수 있습니다.
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();
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다