日期:2014-05-16 浏览次数:20492 次
function Obj(fun){
var self = this;
var func = fun;
var obj = flag;
self.obj = '1';
function sayHello(){
var div = document.createElement("DIV");
div.style.width = '100px';
div.style.height = '100px';
div.style.background = '#0f0';
div.style.top = (obj*100)+'px';
div.style.left = (obj*100)+'px';
div.style.position = 'absolute';
div.innerText = "obj:"+obj;
document.body.appendChild(div);
flag++;
}
self.sayHello = sayHello;
//func && func.apply(self);
/*
func && Jquery.proxy(function(){
alert('a');
func();
}, self);
*/
return self;
}
function c(){
function foo(){
setTimeout('self.sayHello()', 2000 );
}
new Obj(foo);
}
<input type='button' value='Test' onclick="c()" />
function obj(cfg){
config = {
handler:function(){}
};
config['handler'] = cfg['handler'];
function init(){
// statments ...
config.handler();//在这里运行的代码是doHandler的代码
// 那么如何才做到在doHandler写的代码和这里写的代码运行后得到同样的效果?
}
}
function doHandler(){
// statments...
}
function click(){
new obj({handler:doHandler});
}
function Obj(fun){
var self = this;
var func = fun;
var flag = 0;
//self.obj = '1';
function sayHello(){
var obj = flag;
var div = document.createElement("DIV");
div.style.width = '100px';
div.style.height = '100px';
div.style.background = '#0f0';
div.style.top = (obj*100)+'px';
div.style.left = (obj*100)+'px';
div.style.position = 'absolute';
div.innerText = "obj:"+obj;
document.body.appendChild(div);
flag++;
}
//self.sayHello = sayHello;
func && func(sayHello);
/*
func && Jquery.proxy(function(){
alert('a');
func();
}, self);
*/
//return self;
}
function c(){
function foo(f){
var say = f;
setInterval(say, 2000);
}
new Obj(foo);
}
------解决方案--------------------
apply
call
------解决方案--------------------
我看楼主代码
你的想法是
function foo(){
setTimeout('self.sayHello()', 2000 );
}
这个self能指向的是Obj中的self?
------解决方案--------------------
function obj(cfg){
config = {
handler:function(){}
};
config['handler'] = cfg['handler'];
function init(){
// statments ...
config.handler();//在这里运行的代码是doHandler的代码
// 那么如何才做到在doHandler写的代码和这里写的代码运行后得到同样的效果?
doHandler.call(this);
}
}
function doHandler(){
// statments...
}
function click(){
new obj({handler:doHandler});