#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    40
    Rep Power
    0

    Javascript simple problem.


    their are 2 code only the first one works . why???
    whats wrong in second code?

    PHP Code:
    var Mario = {
      
    name'Mario',
      
    sayHello: function(name) {
        return 
    'Hi I\'m ' this.name;
      }
    };
     
    var 
    Luigi = {
       
    name'xoxox'
    };
     
    alert(Mario.sayHello.call(Luigi name)); 


    PHP Code:
    var Mario = {
      
    t'Mario',
      
    sayHello: function(t) {
        return 
    'Hi I\'m ' this.t;
      }
    };
     
    var 
    Luigi = {
       
    t'xoxox'
    };
     
    alert(Mario.sayHello.call(Luigi t)); 
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2011
    Posts
    18
    Rep Power
    0
    You haven't defined a global variable 'name' or 't'. But since window.name is an empty string by default, the first code works.
    Code:
    Mario.sayHello.call(Luigi, name) // name points to window.name which is an empty string
    Mario.sayHello.call(Luigi , t)   // t  points to window.t which is undefined
    This code is sufficient:
    Code:
    var Mario = { 
      name: 'Mario', 
      sayHello: function() { 
        return 'Hi I\'m ' + this.name; 
      } 
    }; 
      
    var Luigi = { 
       name: 'xoxox' 
    }; 
      
    alert(Mario.sayHello.call(Luigi));

    Comments on this post

    • sunny1234567890 agrees : Thanks
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    40
    Rep Power
    0

    Thanks


    Thanks

IMN logo majestic logo threadwatch logo seochat tools logo