简体   繁体   中英

javascript onclick call to function

I'm in the process of learning javascript and was looking at this code:

function foo1 {
  var curObj = this;

    this.foo2 = function() {
         curObj.test = "foo2";
    }

    this.foo3 = function() {
         curObj.test = "foo3";
    }

  // called by
  x.on("click", curObj.foo1)
  x.on("click", curObj.foo2)
}

the "foo2" and "foo3" functions are repetitive so I'd like to replace them with something like:

function setTest(foo) {
  curObj.test = foo;
}

function foo1 {
  var curObj.test;
  x.on("click", setTest(foo));
}

So my question is how do I pass curObj to the function setTest, x.onClick = setTest(this, foo) doesn't working. What if I want to modify other curObj values within the function setTest(), would something like "this" cover that? Is "this" a reference to a memory address or just an object id?

You guys are awesome, thanks for any help you are willing to provide!

I believe what you're looking for is the call() function

function testThis () {
  console.log(this);
}

testThis.call(curObj) // prints curObj

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM