A question about this

Source: Internet
Author: User

varName ="The window";var Object={name:"My Object"; Getname:function () {return  This. Name;};Object. GetName ();//"My Object"(Object. GetName) ();//"My Object"(Object. getname=Object. GetName) ();//"the Window"

Why is it?

      • (object.getName)()is object.getName() equivalent to, because xxx.xxx (member access) has precedence over xxx(xxx) (function call), so adding parentheses does not affect the result (about operator precedence can refer to operator precedence);

      • (object.getName=object.getName)is an assignment expression that evaluates to an assignment expression, 右值 so the value of the expression is getName函数 . You can understand this: (object.getName=object.getName)() equivalence to var b; (b=object.getName)() equivalence var b; b=object.getName; b() ;

      • In strict mode, the This (object.getName=object.getName)() keyword is not allowed to point to the global object because of strict mode.

The this in the function depends on the context in which you invoke it.

    1. When a function is called as a method of an object, this points to the object.

    2. When you execute it directly, this points to the window.

    3. You can also use call , applay bind method to specify this .

Here's an example to help you understand:

var function () {  Console.log (this. name);}; var jack = {  ' Jack ',  Say:say}; var rose = {  ' Rose ',  //  My name is Jack// My name is Rose  = ' window of the World'//  My name is the window of the world

The interesting thing about this writing in the title (object.getName=object.getName)(); is that the object.getName=object.getName return result of the assignment operation is the body of the following function,

function () {    returnthis. Name;}

So the result of the whole sentence is equal to

(function() {    returnthis. Name;}) ();

In conjunction with this answer, the 2nd point mentioned above, this it is pointed out here window .

A question about this

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.