2012-02-10 196 views
1
function _(e) { 
    if (typeof e == 'string') { 
     if (e.charAt(0) == '#') { 
      return document.getElementById(e.slice(1)); 
     } else if (e.charAt(0) == '.') { 
       var c = document.getElementsByClassName(e.slice(1)); 
      return (c.length==1)?c[0]:c; 
     } else { 
       var t = document.getElementsByTagName(e); 
      return (t.length==1)?t[0]:t; 
     } 
    } else { 
    console.log('Error. Not a valid string in _.'); 
    } 
} 

_.prototype.hide = function() { 
//testing 
console.log(this) 
} 

該功能工作正常,但是當我嘗試添加方法隱藏並嘗試並調用它像_('#menu').hide();時,它會拋出錯誤:TypeError: Object #<HTMLDivElement> has no method 'hide'我誤解了什麼?爲什麼這個原型失敗?

是的,我沒有谷歌這個問題,我只是不明白。一個提示將不勝感激。

+0

它在我看來像你試圖調用隱藏的返回值功能。我期望:var x = new _('#menu'); x.hide();去工作,但我不認爲這就是你想要的。也許你應該返回一個對象來調用隱藏功能。 – jjrdk 2012-02-10 09:52:58

+0

必須在'hide()'中設置'return' – diEcho 2012-02-10 09:53:41

回答

0

您將構造函數用作常規函數,因此它不會創建對象,它只會返回您指定的對象。

你可以使用它作爲一個普通的功能,但你需要調用自身的構造函數來創建返回對象,並處理當它作爲一個構造函數:

function _(e) { 
    if (!this instanceof _) { 
    if (typeof e == 'string') { 
     if (e.charAt(0) == '#') { 
     return new _(document.getElementById(e.slice(1))); 
     } else if (e.charAt(0) == '.') { 
     var c = document.getElementsByClassName(e.slice(1)); 
     return new _((c.length==1)?c[0]:c); 
     } else { 
     var t = document.getElementsByTagName(e); 
     return new _((t.length==1)?t[0]:t); 
     } 
    } else { 
     console.log('Error. Not a valid string in _.'); 
    } 
    } else { 
    this.elements = e; 
    } 
} 

你可能會考慮到總是爲元素使用數組,即使它是單個元素。現在elements屬性將是一個元素或一組元素,所以你必須在每次使用它時檢查這個...

+0

'hide()';你沒有提到 – diEcho 2012-02-10 10:03:45

+1

@diEcho:這部分代碼不需要改變。 – Guffa 2012-02-10 10:35:20

+0

謝謝,這隻會破壞第一個函數的簡單性,因爲它不直接返回元素 – jenswirf 2012-02-10 10:41:06

1

構造函數需要返回自身( return this;)。目前它返回一個DOM對象,或者如果沒有字符串被傳遞,則返回 undefined

試試這個:

function _(e) { 
    if (!(this instanceof _)){ 
    return new _(e); 
    } 

    if (typeof e == 'string') { 
    if (e.charAt(0) == '#') { 
     this.el = document.getElementById(e.slice(1)); 
    } else if (e.charAt(0) == '.') { 
     var c = document.getElementsByClassName(e.slice(1)); 
     this.el = (c.length==1)?c[0]:c; 
    } else { 
     var t = document.getElementsByTagName(e); 
     this.el = (t.length==1)?t[0]:t; 
    } 
    return this; 
    } else { 
    console.log('Error. Not a valid string in _.'); 
    throw e + ' is not a valid string'; 
    } 

} 

_.prototype.hide = function() { 
    console.log(this); 
} 

您可以調用構造函數,像這樣:

e = _('#myDiv'); 
e.hide(); 
+0

由於該函數被用作普通函數,而不是構造函數,'this'將是全局作用域,即'window'。 – Guffa 2012-02-10 10:08:48

+0

我以前的回答很差。我又去了一次。 – osahyoun 2012-02-10 10:15:24

+0

你可以直接調用構造函數'_('myDivID')',它會返回一個'_'的實例,我認爲這是你想要的。比不得不調用它好得多:'el = new _('myDivID');' – osahyoun 2012-02-10 10:17:38

-2

嘗試定義你這樣的功能:

var _ = function (e) { }; 

編輯 而是的,別忘了當然返回this

+0

沒有必要這麼做 – diEcho 2012-02-10 09:53:16