这个内部函数 [英] this inside function

查看:23
本文介绍了这个内部函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是:

function Foo()
{
   this.foo = "bar"; // <- What is "this" here?
}

据我所知,它取决于 Foo 的使用方式,即作为构造函数还是作为函数使用.this 在不同情况下可以是什么?

From what I can tell it depends on how Foo is used, i.e. as a constructor or as a function. What can this be in different circumstances?

推荐答案

this 关键字指的是函数所属的对象,如果是函数,则是 window 对象不属于任何对象.

The this keyword refers to the object the function belongs to, or the window object if the function belongs to no object.

在OOP代码中使用,引用函数所属的类/对象例如:

It's used in OOP code, to refer to the class/object the function belongs to For example:

function foo() {
    this.value = 'Hello, world';

    this.bar = function() {
        alert(this.value);
    }
}

var inst = new foo();
inst.bar();

这个提醒:Hello, world

您可以使用apply()call() 函数来操作this 引用的对象.(有时非常方便的功能)

You can manipulate which object this refers to by using the apply() or call() functions. (A very very handy feature at times)

var bar1 = new function() {
    this.value = '#1';
}
var bar2 = new function() {
    this.value = '#2';
}

function foo() {
    alert(this.value);
}

foo.call(bar1); // Output: #1
foo.apply(bar2, []); // Output: #2

这篇关于这个内部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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