2011-04-18 103 views
0

我想用我的父函数有一个值。这可能是一个愚蠢的问题,但我一直无法找到如何做到这一点的直接教程。使用原型在Javascript中继承

我知道,在使用原型有可能

function handler (selector) { 
    return selector; 
} 
Object.prototype.alertLine = function() { 
     alert(this);} 

handler('hello').alertLine(); 

,仍然收到警报。但我想知道是否有指定的父的功能,例如对象,刺痛,数

function handler(selector) { 
if (typeof(selector) == 'string'){ 
return String(selector); 
} 

if (typeof(selector) == 'number') { 
return Number(selector); 
} 

if (typeof (selector) == 'object') { 
return Object(selector); 
} 
} 

handler.prototype.alertLine = function() { 
alert(this); 
} 

handler('hello').alertLine(); 

我不介意Handler为对象的方式或者不是唯一的问题,如果我传递值使用这种方法。

谢谢你提前。

回答

0

“我们的想法是为人每次重新初始化一个新的对象在一个代码行,从而代替一个变种=新处理程序(‘你好’); a.alertLine();代替这个我想改变这个风险价值=新的处理程序;然后引用到一个新的参数,每次(“你好”)alertLine()”

我真的不知道为什么你要。这样做,但这样的事情可能会帮助你:

var Handler = function() { 
    var fun = function() {} 
    fun.prototype.set = function(t) {this.t = t; return this;} 
    fun.prototype.alertLine = function(){ alert(this.t); } 
    return new fun; 
} 

var a = Handler(); 
a.set('foo').alertLine(); 

http://jsfiddle.net/herostwist/yPSpT/

1

如果你想做这样的事情,你需要实例化一个处理程序的对象,而不是将其用作方法。你想要一个function constructor

function Handler(selector){ 

if (typeof(selector) == 'string'){ 
    this.selector = String(selector); 
} 

if (typeof(selector) == 'number') { 
    this.selector = Number(selector); 
} 

if (typeof (selector) == 'object') { 
    this.selector = Object(selector); 
} 

} 

Handler.prototype.alertLine = function(){ 
    alert(this.selector); 
} 

var h = new Handler("hello"); 
h.alertLine();