Merge two functions?

后端 未结 5 1178
礼貌的吻别
礼貌的吻别 2021-01-24 04:32

Say, I have two functions:

function foo() {
  this.lorem = \'ipsum\';
}

function boo() {
  console.log(this.lorem);
}

And I want to insert the

相关标签:
5条回答
  • 2021-01-24 04:40

    In the event you want to keep them separate:

    function foo() {
      this.lorem = 'ipsum';
      boo(this);
    }
    
    function boo(element) {
      console.log(element.lorem);
    }
    
    0 讨论(0)
  • 2021-01-24 04:40

    Wrap them both under the same context:

    var myClass = {
        foo: function foo() {
            this.lorem = 'ipsum';
            this.boo();
        }, boo: function boo() {
            alert(this.lorem);
        }
    };
    

    Then to activate foo:

    myClass.foo();
    

    Live test case.

    0 讨论(0)
  • 2021-01-24 04:42

    If you don't want to modify the existing functions do this:

    function foo() {
      this.lorem = 'ipsum';
    }
    
    function boo() {
      console.log(this.lorem);
    }
    
    
    function bar() {
        boo.call(new foo);
    }
    
    bar();
    

    Here's a JSFiddle of it in action: http://jsfiddle.net/8Wb6T/

    0 讨论(0)
  • 2021-01-24 04:45

    Like this?

    function foo() {
        this.lorem = 'ipsum';
        console.log(this.lorem);
    }
    

    In all seriousness, your question is not clear enough to be reliably answered.

    0 讨论(0)
  • 2021-01-24 04:57
    function foo() {
      this.lorem = 'ipsum';
      boo.call(this);
    }
    
    function boo() {
      console.log(this.lorem);
    }
    
    foo();
    
    0 讨论(0)
提交回复
热议问题