开发者

Merge two functions?

开发者 https://www.devze.com 2023-03-28 21:28 出处:网络
Say, I have two functions: function foo() { this.lorem = \'ipsum\'; } function boo() { console.log(this.lorem);

Say, I have two functions:

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

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

And I want to insert the boo function at the end of the foo function so that they can share the same this. How would I do it? 开发者_JS百科


Like this?

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

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


In the event you want to keep them separate:

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

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


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.


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

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

foo();


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

精彩评论

暂无评论...
验证码 换一张
取 消