2013-05-16 173 views
0

我有showProfile函数,它是接受回调函数。作为对象属性的传递函数(具有回调函数(有参数))

回调函数也有一个对象的区段。

showProfile(call_back_fn) 

调用它:

showProfile(function(obj){console.log(obj)}) 

我要将此功能作为属性Person对象:

function Person(name,age,showProfile){ 
     this.name=name ; 
     this.age=age; 
     /* 
     this.showProfile=showProfile ??? 
       OR 
     this.prototype.showProfile=showProfile ??? 
       OR What ??  
*/ 

       return this;   
    } 

然后,创建一个Person对象:

var p=new Person('Abdennour',23,fnshowProfile); 

我如何使这个功能(显示配置文件)作为对象属性。如果可能,如何传递它的参数(这是一个回调函数)? 然后,如何呼叫fnshowProfile这是在上面的片段。

UPDATE

否则,如果我创建了一个Person对象为follwoing:

var p=new Person('Abdennour',23,showProfile()); 

我怎么能访问showProfile添加一个回调函数作为参数: 的d那么,如何能我从p对象执行showProfile。

+1

这是有点不清楚,你可能会js为此做些什么吗? –

+0

我编辑问题的标题:传递函数(具有回调函数(有参数))作为对象属性。 –

+0

另请参阅更新后编写的文字 –

回答

0

是的,我发现它:
演示http://jsfiddle.net/abdennour/5vNQ5/

callbackshowProfile=function(obj){ 
    alert(obj['field1']); 

} 

showProfile=function(cfn){ 
    cfn(); 
} 


function Person(name,age,shfn,callback){ 
this.name=name; 
    this.age=age; 
    this.shfn=shfn; 
    this.callback=callback; 
    return this; 
} 

创建一个Person对象:

var pp=new Person('Abdennour',13,showProfile,callbackshowProfile) 

要调用showProfile其中有回调函数的参数,这是有一个对象作为参数。

pp.shfn(pp.callback.bind(null,{field1:'My field 1'})) 
相关问题