'this'关键字,不清楚 [英] 'this' keyword, not clear

查看:130
本文介绍了'this'关键字,不清楚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下代码中的''关键字感到困惑,有两个'this':

I get confused about 'this' keyword in the following codes, there are two 'this':

var Foo = function(string){
  this.name=string // 1st-this
}

Foo.prototype.get_name = function(){
  return this.name // 2nd-this
}

var myFoo = new Foo('John')

the_name=myFoo.get_name()

' the_name '等于'John',原型方法获取返回 this.name 的名称。但有人可以向我解释第1个 - 这个和第2个这个,它们代表什么?

'the_name' is equal to 'John', the prototype method get the name by return this.name. But can anyone explain to me the 1st-this and 2nd-this, what do they stand for?

推荐答案

在Javascript中,这个的值取决于你调用函数的方式

In Javascript, the value of this is dependent on the way you call the function.

有五种方法可以在JS中调用函数,它们都对有影响

There are 5 ways to call a function in JS, and they all have effect on this:


  1. new Foo(); < =这里,你正在创建一个新对象,并且将反映该新对象

  2. Foo(); < =此处,你按原样调用函数,这个将是全局对象(!)

  3. var obj = {foo:Foo};

    obj.foo();
    < =这里,你将函数作为的方法调用OBJ ; obj

  4. Foo.call (thisObject,arg1,arg2); < =此处,您可以在第一个参数
  5. $ b中指定的值$ b
  6. Foo.apply(thisObject,[args]); < =这里,你可以指定这个在第一个参数中

  1. new Foo(); <= here, you’re creating a new object, and this will reflect that new object
  2. Foo(); <= here, you're calling the function as-is, and this will be the global object(!)
  3. var obj = { foo: Foo };
    obj.foo();
    <= here, you're calling the function as a method of obj; this will be obj
  4. Foo.call(thisObject, arg1, arg2); <= here, you can specify the value of this in the first argument
  5. Foo.apply(thisObject, [args]); <= here, you can specify the value of this in the first argument

在4和5中,调用 apply call ,你需要分别传递所有参数,而使用 apply ,你可以传递一个包含所有参数的数组。

In 4 and 5, the difference between call and apply is that with call, you need to pass all the arguments separately, whereas with apply, you can pass an array containing all the arguments.

注意,在上面的例子2中,函数应该被称为 foo 而不是 Foo 。由于不可能知道是否应该使用 new 来调用函数,所以一致意见是如果它是构造函数则用大写字母启动函数名称(并应与 new 一起使用);否则,它应该以小写字母开头。

Note that in my example 2 above, the function should have been called foo instead of Foo. Since it’s impossible to know off-hand whether a function is supposed to be called with new or not, the consensus is to start the function name with a capital letter if it’s a constructor (and should be used with new); otherwise, it should start with lowercase.

这篇关于'this'关键字,不清楚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆