2012-02-03 4 views
1

이 질문에 관련되는 함수 둘 다 OOP 문법과 객체 : How to implement chained method calls like jQuery?자바 스크립트 var에 나는 이전에 여기에 질문

내가 거기에 약간의 시간에서 확인 응답에서이 방법을 사용하고있다, 그리고 잘 작동합니다. 그러나 필자는 툴킷의 구문을 훨씬 더 변경하고 싶습니다.

  1. foo(firstarg).bar(secondarg); // should function as the question above.

  2. foo(onlyarg).bar // a function with one argument

  3. foo.bar(onlyarg); // should also work, when a first argument is not appropriate.

  4. foo.bar; // a function without an argument, or returns a static value.

나는 동일을 작동하는 4 syntaxs 싶습니다 foo 객체이지만 OOP 이해가 부족합니다. 나는 몇 가지 시도를 해왔고, 지금까지 나는 1 & 2를 사용할 수 있고 3 & 4를 사용할 수는 있지만 모두 함께 작동하는 것은 아닙니다. 또한 각 함수가 루트 객체를 반환하도록하여 chaining을 옵션으로 남겨두면 좋을 것입니다.

편집 :

var main = function(obj){ this.obj = obj; }; 
var tool = function(obj){ return new main(obj); }; 
main.prototype = { 
     alertThisPlus : function(plus){ 
      alert(this.obj + ' ' + plus);  
     }, 
     alertJustThis : function(){ 
      return alert(this.obj); 
     } 
}; 

사용을 내가 좋아하는 것이 무엇

tool('hello').alertThisPlus('world'); // returns alert('hello world') 
tool().alertJustThis('hello world'); // returns alert('hello world'); 

이하는 것입니다 :

tool('hello').alertThisPlus('world'); // returns alert('hello world') no change 
tool.alertJustThis('hello world'); // returns alert('hello world') does not work 
을 나는 분명히 여기에 내가 지금 무엇을하고,보다 구체적으로 필요
+0

이것은 실제로 OOP가 아니지만 음소거 지점입니다. 3과 4는'bar'가 함수가 아니면 호환되지 않습니다. 그것들을 호환 가능하게 만드는 최선의 방법은 인자없이'bar'를 호출하는 것입니다. 1과 2와 마찬가지로. –

+1

. 나는 이미 1 & 2 작업을하고 있으며 3 & 4 작업이 이미 있습니다. 그 모든 일을 즉시하고 있습니다. 나는 jquery로 인해 가능하다는 것을 안다. 예를 들어 $ (arg) .foo와 $ .browser가 모두 작동한다. – Fresheyeball

답변

3

기능은 기능 '도구'를 추가 할 수 있습니다, 그래서 그냥 개체입니다. 이 작업은 수동으로 수행 할 수 있습니다.

tool.foobar = function() {}; 

또는 클래스가 적절하게 구조화되어있는 경우 혼합 방식을 사용할 수 있습니다. 다음과 같은 것 :

function Tool(prefix) { 
    this.prefix = prefix; 
} 

Tool.prototype.alertThisPlus = function(suffix) { 
    alert((typeof this.prefix != 'undefined' ? this.prefix + ' ' : '') + suffix); 
}; 

Tool.prototype.alertJustThis = function(msg) { 
    alert(msg); 
}; 

function tool(prefix) { 
    return new Tool(prefix); 
} 

// Mix-in the methods from a static instance of Tool onto the 'tool' function. 
// This makes both tool.alertThisPlus() and tool.alertJustThis() available, 
// both will be called in the context of 'staticTool'. 
(function() { 
    var staticTool = new Tool(); 
    for (var o in staticTool) { 
    if (typeof staticTool[o] == 'function') { 
     tool[o] = staticTool[o].bind(staticTool); 
    } 
    } 
})(); 

tool('hello').alertThisPlus('world'); // returns alert('hello world') 
tool().alertJustThis('hello world'); // returns alert('hello world') 
tool.alertJustThis('hello world'); // returns alert('hello world') 
+0

참고 :'Function.bind()'는 모든 브라우저에서 아직 지원되지 않고 있으므로 클로저를 사용하거나 직접 바인드 함수를 작성해야 할 수도 있습니다. – Dan

+0

이 부분 이외의 모든 것을 이해합니다. (function() { var_t staticTool = new Tool(); if (staticofool typeof) { 도구 {] = staticTool [o] .bind (staticTool); } } })(); – Fresheyeball

+0

그곳에서 무슨 일이 벌어지고 있는지 설명해 주시겠습니까? – Fresheyeball

0

내가 생각할 수있는 유일한 방법은 괄호없이 함수를 실행할 수있게하는 것이다. a) callb ack param 또는 b) 자체 실행을 허용합니다.

var foo = (function() { 
    alert('foo called'); 
})(); 

단계를 더 진행하면 값을 반환하기 위해 일부 클로저를 사용했다고 가정 해 보겠습니다.

var foo = (function() { 
    return { 
    bar: "arf arf said the dog" 
    } 
})(); 

이제 사용할 수 있습니다

foo.bar;