原型方法不是一个函数,为什么

prototype method is not a function,why?

本文关键字:一个 函数 为什么 方法 原型      更新时间:2023-09-26
(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
}

我想将函数和类移到就绪函数中以使代码清理并节省内存,但我发现类方法不起作用。

如果我将原型移动到测试功能,它可以工作,例如

(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); 
}

为什么我必须移动原型方法来测试或准备功能?

因为你的.prototype.mod定义是在调用它的函数之后。提升只有助于功能定义本身(这就是为什么new Class()工作正常),而不是原型定义。

这真的不应该那么难:先准备你的工具,然后使用它们。