Roy
Roy

Reputation: 751

prototype method is not a function,why?

(function(){
  test();
}());

function Class(){
  this.prop = 'hi';
}
Class.prototype.mod = function(num){this.prop = num;}

function test(){
  var c = new Class();
  c.mod('now'); // it'll say it's not a function
  alert(c.prop); // it's work
}

I wanna move function and class out to ready function to make code clean up and save memory, but I found the class method does not work.

If I moved prototype to test function, it work, like

(function(){
  test();
}());

function Class(){
  this.prop = 'hi';
}


function test(){
  Class.prototype.mod = function(num){this.prop = num;}
  var c = new Class();
  c.mod('now'); // it's ok
  alert(c.prop); 
}

why I must to move prototype method to test or ready function?

Upvotes: 2

Views: 8202

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

Because your .prototype.mod definition is after the function that calls it. Hoisting only helps for the function definition itself (which is why new Class() works fine), not for prototype definitions.

This really shouldn't be so hard: prepare your tools first, then use them.

Upvotes: 5

Related Questions