简体   繁体   中英

How do i call a function of an object as if it was the property of another object?

Now this may be an odd question, but consider the following:

var A = {
  name: "A",
  showName: function(){console.log(this.name)}
}

var B = {
  name: "B"
}

I now want to call the "showName" function of A as if it was a property of B, meaning it should log "B" to the console. Is there any reasonable way to accomplish this?

只需使用call

A.showName.call(B);

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