"this" in a javascript function? -


I understand that "this" is a reference to the caller object.

See "this" in the code:

  var person = function () {this.name = "foo"; }  

But then I saw these lines of code:

Example 1:

  function Hello world 1 () {Body: "Hello world!"}) (); Example: 2:  

I also saw this code:

  Function Hello World 2 () {This ({Body: "Hello,"}} ({body: "world!"}) ();  
  • What is happening in the above examples?

    Actually this can refer to a different matter , Undoubtedly, it is determined how you open a function, for exmaple:

      obj.func ();  obj   obj  contains   

    this value.

      new fax ();   

    This value will refer to a newly created object that is derived from Func.prototype .

      function ();  

    This value will reference the global object.

    And the value can also be set clearly , for example call or apply methods By using,

      function fu () {alert (this); } Foo.call ("Hello world");  

    Hello World 1 for example you post, will work only if this this value refers to a function , Which gives another function, because you analyze the line:

      this ({body: "Hello World!"});  

    You can keep in mind that the this function needs to be, because you're passing this object, the object is passing it. And we know that the return value also needs to be a function, because the last bracket is another function call.

    For example:

      var fn = function (o) {return function () {alert (OOB); }}; HelloWorld1.call (fn); // or equivalent fn.method = Hello World 1; Fn.method ();  

    Edit : Hello World 2 for example, to post the job, this value The function should be called without any arguments, such as:

      var fn = (function () {var msg = ''; return function in (o) {if (o) {// has been called with an argument? Msg + = o.body;} other {// no, show message alert; / a reference to himself back;}}) (); Hello World 2 (Function Hello World 2) (It's (body: "hello,"}) ({body: "Mary"} ({body: "world!"})}} Hello World 2. Call (FN) "// hello my world!"  

  • Comments