dcsimg
www.webdeveloper.com
Results 1 to 2 of 2

Thread: Determing if a program returns true

  1. #1
    Join Date
    Apr 2008
    Posts
    146

    Determing if a program returns true

    Trying to determine if the program below returns true. I say yes but want to know if my explanation is correct.

    b calls function Builder() which then reads this.self. this refers to the object self which invokes function(). Then return this is read which passes back the value of this to the calling function.

    With b.self(), b refers to the object self() which invokes function() and again takes you to return this

    Correct?

    Code:
    function Builder () {
       this.self = function () {
          return this;
       }
    }
    b = new Builder();
    console.log(b.self() === b);

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,532
    Break it down...

    Code:
    function Builder () {
       this.self = function () {
          return this;
       }
    }
    b = new Builder();
    console.log(b.self() === b);
    b = new Builder(); which runs the function and sets a function with a property of .self which is a function that returns a reference to the calling object via this and because b is an object with a function that returns a reference to the caller of this which will be the variable b, the function will return true.

    A simple change in
    Code:
    function Builder () {
       this.self = function () {
          return this.self;
       }
    }
    b = new Builder();
    console.log(b.self() === b);
    will return false and if you return the function call, you get a browser error when the stack limit is exceeded.

    I hope this answers your query.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center