Javascript文字对象表示法this vs Object Name [英] Javascript Literal Object Notation This vs Object Name

查看:73
本文介绍了Javascript文字对象表示法this vs Object Name的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的对象文字:

I have an object literal like this:

var test = {
    one: function() {
    },
    two: function() {
        this.one(); // call 1
        test.one(); // call 2
    }
};

two函数中的调用(使用对象文字名称与使用this)之间的区别是什么?

What is the difference between the calls in the two function (using the object literal name versus using this)?

推荐答案

test始终在two函数的闭包内绑定到变量test,而this取决于函数的调用方式.如果使用常规对象成员访问语法调用该函数,则this成为拥有该函数的对象:

test is always bound within the closure of the two function to the variable test whereas this depends on how the function is called. If the function is called using the regular object member access syntax, this becomes the object owning the function:

test.two(); // inside, "this" refers to the object "test"

您可以使用Function.prototype.call更改this的值:

test.two.call(bar); // inside, "this" refers to the object "bar"

但是test的值在two函数内部保持不变,无论该函数如何调用.

But the value of test remains the same inside the two function, regardless of how the function is invoked.

这篇关于Javascript文字对象表示法this vs Object Name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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