SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict ketting00's Avatar
    Join Date
    Jul 2011
    Posts
    325
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)

    Why this function in object method isn't work

    I have two arrays which I want to match them together as below:
    Code:
    var a = [1, 2, 3, 4];
    var b = [5, 6, 7, 8];
    This method works:
    Code:
    for ( var i = 0; i < 4; i += 1 ) {
    	(function(z) {
    		var d = x(a[z], b[z]);
    	})(i);
    }
    
    function x(j, k) {
    	console.log(j, k);
    };
    But I also want this method to work as well:
    Code:
    for ( var i = 0; i < 4; i += 1 ) {
    	(function(z) {
    		var d = x.y(a[z], b[z]);
    	})(i);
    }
    
    var x = {
    	y: function(j, k) {
    		console.log(j, k);
    	}
    };
    Upon testing it throws error.
    I woulds use the second method because most of my JavaScript code adopting the pattern.

  2. #2
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,268
    Mentioned
    18 Post(s)
    Tagged
    0 Thread(s)
    The second example fails because "x" isn't defined until after the for loop has run. Move "x" above the for loop, and it should be fine.

    The only reason the first example works is because function declarations are special. JavaScript makes a point to look for and process those before it runs any regular code. The term "hoisting" is often used to describe this behavior. Function declarations behave as if they were hoisted to the top of your code.
    "First make it work. Then make it better."

  3. #3
    SitePoint Addict ketting00's Avatar
    Join Date
    Jul 2011
    Posts
    325
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Thank you for the info and explanation.


Bookmarks

Posting Permissions

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