admin管理员组文章数量:1388116
(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?
(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?
Share Improve this question asked Jan 22, 2015 at 22:46 RoyRoy 7613 gold badges11 silver badges24 bronze badges 2-
1
The fact that you call it "ready function" seems to suggest you think the self-executing function (
(function(){...}())
) waits for the page to load before executing, which is not true. – JJJ Commented Jan 22, 2015 at 22:49 - as you say, it's self-executing function and I make this js script bottom of page, like ready. is it good to make everything in self-executing function I wanna know, thx – Roy Commented Jan 23, 2015 at 2:07
1 Answer
Reset to default 5Because 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.
本文标签: javascriptprototype method is not a functionwhyStack Overflow
版权声明:本文标题:javascript - prototype method is not a function,why? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744497662a2609129.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论