简体   繁体   中英

Why can't I use this.arguments, while arguments work?

function MyArray() {
    var self = this.arguments; //<---
    this.toString = function() {
        return self;
    };

}

var c = new MyArray(2, 3, 1, '232');
console.log(c.toString());

undefined

function MyArray() {
    var self = arguments; //<---
    this.toString = function() {
        return self;
    };

}

var c = new MyArray(2, 3, 1, '232');
console.log(c.toString());

[2,3,1,'232']

So, why is that so? What is the difference between this.arguments and arguments ?

There is no this.arguments . However arguments is an array-like object which always exists inside functions and refers to the arguments given in the call.

In JS, this represents "calling context", which can be set a number of different ways. It has really nothing to do with variable scope. They're entirely separate concepts. That's why arguments is available as a variable, but not a property of this .

The value of this varies based on how a function is called.


Called as a method

For example, if I do...

my_obj.myMethod();

...then this will refer to my_obj because the function myMethod was called from the context of my_obj .


Called independently as a function

but if I do...

var m = my_obj.myMethod;
m();

Even though my_obj and myMethod are the same code as the first example, the value of this will usually change to the global object.


Called using .call or .apply

There are several other ways this can be set as well.

m.call(my_other_obj, "more", "args");

m.apply(my_other_obj, ["more", "args"]);

Using .call or .apply , the first argument passed becomes the value of this . The difference between the two is how the rest of the arguments are passed.


Created using .bind

There's also .bind() which takes arguments in the same manner as .call() , but creates and returns a new function with the this value and any other arguments permanently set.


Called using the new operator

The final way is when you call a function as a constructor. To do this, you use the new operator.

var new_obj = new m;

var new_obj = new obj.m;

In both cases, the value of this will be a new object being constructed. YOu should never use new unless the function called has been set up to be used as a constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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