这个里面的功能 [英] this inside function

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

问题描述

我的问题是:
$ b $

 函数Foo()
{
this.foo =bar ; //< - 这里是什么这个?
}

从我能告诉它取决于 Foo 被使用,即作为构造函数或函数。 这个在不同的情况下可以做什么?

解决方案 这个关键字指向函数所属的对象,或者如果函数不属于任何对象,则指向窗口对象。



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

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

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

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

这个提示: Hello,world



您可以通过使用 apply()来操作哪个对象这个 $ c>或 call()函数。

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

函数foo(){
alert(this.value);
}

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


My question is:

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

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?

解决方案

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

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();

This alerts: Hello, world

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天全站免登陆