2011-04-18 102 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();