简体   繁体   English

如何访问其他对象的功能

[英]How do I access a function of a different object

I have the following code - 我有以下代码 -

function test() {
        a = {
            name : 'John',
            greeting : 'Hello',
            sayIt : function() {
                return this.greeting + ', ' +
                    this.name + '!';
            }
        };

        b = {
            name : 'Jane',
            greeting : 'Hi'
        };
}

How can I access sayIt using b? 如何使用b访问sayIt? Ofcourse b.sayIt will not work. 当然b.sayIt将无法正常工作。 I need to print 'Hi Jane'. 我需要打印'Hi Jane'。 How can I pass the name and greeting of b to sayIt function? 如何将b的名称和问候语传递给sayIt函数?

You can use apply or call . 您可以使用applycall

a.sayIt.apply(b);

These change the value of this . 这些改变了this的价值。

You need to return a and b from the function. 您需要从函数返回ab Then you can do this: 然后你可以这样做:

function test() {
  var a = {
    name : 'John',
    greeting : 'Hello',
    sayIt : function() {
      return this.greeting + ', ' +
      this.name + '!';
    }
  };

  var b = {
    name : 'Jane',
    greeting : 'Hi'
  };

  return this;
}

test().a.sayIt.call(test().b); // Hi Jane!

DEMO DEMO

You also could use 你也可以使用

b = new a();
b.name = 'Jane',
b.greeting = 'Hi'
b.sayIt();

使用Function.prototype.apply

a.sayIt.apply(b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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