简体   繁体   English

在这种情况下,为什么要使用call()方法?

[英]Why would I use the call() method in this case?

So I am kind of having a hard time understanding when the appropriate time to use the call() method would be. 因此,我很难理解何时应该使用call()方法。

I found this example online: 我在网上找到了这个例子:

var person1 = { name: 'Chris' };
var sayName = function() { console.log(this.name) };

// How to use call method
sayName.call(person1)

I understand that the example above allows you to set the context for "this", but why not just pass the person as a param instead, like so: 我知道上面的示例允许您为“ this”设置上下文,但是为什么不将人作为参数传递,就像这样:

var sayName = function(person) { console.log(person.name) };
sayName(person1);

Could someone help me understand why you would use the call() method as opposed to just passing the person as a param? 有人可以帮助我了解您为什么要使用call()方法,而不是仅仅将其作为参数来传递吗?

If it is just the name of the person you will have to output in your app, then, of course, using call instead of passing the name as an argument doesn't make any sense. 如果仅是您必须在应用程序中输出的人员的姓名,那么,当然,使用call而不是将姓名作为参数传递毫无意义。

But, imagine a situation where you have a context with 25 different fields. 但是,想象一下您有一个包含25个不同字段的上下文的情况。 Would you pass all 25 fields as arguments? 您是否将所有25个字段都作为参数传递?

Also, imagine a function which adds the name property to a context: 另外,想象一个将name属性添加到上下文的函数:

function person(firstName) {
   this.name = firstName;
}

me = {}
teacher = {}

person.call(me, 'Charlie');
person.call(teacher, 'John')

Besides, the person function can now be used as a constructor. 此外, person函数现在可以用作构造函数。

   var someone = new person('Mary')

The usage of call and apply methods really transcends simple scenarios such as name printing. callapply方法的使用确实超越了诸如名称打印之类的简单方案。 The best way to explore the usefulness of these function is to learn JS OOP. 探索这些功能有用性的最好方法是学习JS OOP。

When we speak about prototypes and classes, you can always think that calling function always passing left part of calling expression (before dot) to "hidden" this argument: 当我们谈论原型和类时,您总是可以认为,调用函数总是将调用表达式的左部分(点之前)传递给“隐藏”此参数:

  1. myObj.someFunc() -- myObj myObj.someFunc()-myObj
  2. someFunc() // strict -- undefined someFunc()//严格-未定义
  3. someFunc() // unstrict -- window/global someFunc()//不受限制-窗口/全局

But in your case, sayName function is not associated to project, so probably you want to achieve this: 但是在您的情况下, sayName函数未与项目关联,因此您可能想要实现以下目的:

var person1 = { name: 'Chris' };
var sayName = function() { console.log(this.name) };

// you can imagine this as very simplified version of "call fn" do internally
person1.sayName = sayName; 
person1.sayName(); // logs 'Chris'

It's just a programmer choice how to implement your code. 这只是程序员选择如何实现代码的选择。 At your case function is not binded to object, so you should specify how to pass context, implicit or explicit, and passing it implicit (via left part of dot) doesn't make language less or more functional. 在您的情况下,函数没有绑定到对象,因此您应该指定如何传递上下文(隐式或显式),并隐式地(通过点的左部分)传递上下文不会降低语言的功能。

If you use ES6+ env. 如果您使用ES6 + env。 you should probably forget about the call and apply methods at most cases. 在大多数情况下,您可能应该忘记调用并应用方法。

class Person {
  constructor(name) {
    this.name = name;
  }

  someFunc() {
    console.log(this.name);
  }
}

let person1 = new Person('Chris');
person1.someFunc(); // logs 'Chris'

let refToFn = person1.someFunc;
refToFn(); // error, because no implicit (via dot) or explicit (via arg) context passing

For example "Python" has opposite paradigm, you should always pass "this" ("self" at args) context to the method: 例如,“ Python”具有相反的范例,您应该始终将“ this”(args中的“ self”)上下文传递给该方法:

def someFunc(self):
  print self.name;

The real question maybe you want to ask is why "this" context is exist in javascript. 您可能要问的真正问题是,为什么JavaScript中存在“此”上下文。

Answer is: At first tell me why you need if you pass direct object reference then use call() function? 答案是:首先告诉我为什么需要传递直接对象引用然后使用call()函数?

See below, you can do that easily even no need any .call() when you passing direct any object: 参见下文,当您直接传递任何对象时,甚至不需要任何.call()都可以轻松做到这一点:

var person1 = { name: 'Chris' };
var sayName = function(obj) { console.log(obj.name) };
sayName(person1);

You should know the purpose why we using .apply() , .call() etc. One of the purpose of borrowing the mathod from one object to another. 我们为什么使用你应该知道的目的.apply() .call()等。其中的借款马托从一个对象到另一个对象的目的。

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

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