日期:2014-05-16 浏览次数:20340 次
person.js文件中的代码 var person = function (name) { var name = name; this.onRun; this.run = function () { onRun(name); } }
<html> <head> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <script type="text/javascript" src="person.js"></script> <script type="text/javascript"> function run(name) { alert(name + "在奔跑"); } var person; $(documen).ready(function () { person = new person("刘德华"); person.onRun = run; //这里绑定事件方法,应该这么说 person.run(); //这里会触发事件 }); </script> </head> <body> <div>test page</div> </body> </html>
var person = function (name) { this.name = name; this.onRun = function(){}; this.run = function(){this.onRun(this.name)} } function run(name) { alert(name + "在奔跑"); } var person = new person("刘德华"); person.onRun = run; person.run();
------解决方案--------------------
把方法传递进去就行:
var person = function (name) { this.name = name; this.run = function(method){method.apply(this)} } var person = new person("刘德华"); person.run(function(name) { alert(this.name + "在奔跑"); });
------解决方案--------------------
这不更简单吗?
var person = function (name) { this.name = name; this.onRun = function() {}; this.run = function(){ this.onRun() } } function run(name) { alert(this.name + "在奔跑"); } var person = new person("刘德华"); person.onRun = run; person.run();
------解决方案--------------------
this.run = function () {
//onRun(name); 错误在这 没加 this
this.onRun(name);
}
另外下面document也拼错了
------解决方案--------------------
var person = function (name) { this.name = name; this.onRun = function() {}; this.run = function(){ this.onRun() } } function runX(name) { alert(this.name + "在奔跑"); } function runY(name) { alert(this.name + "在睡觉"); } var personQ = new person("刘德华"); personQ.onRun = runX; personQ.run(); personQ.onRun = runY; personQ.run(); var personR = new person("周星驰"); personR.onRun = runX; personR.run(); personR.onRun = runY; personR.run();