2013-09-01 43 views
-1

我有這個Javascript類,並想爲此類的屬性添加某種功能(如原型) 。爲javascript屬性定義函數

function theUploader(virtualField) 
{ 
    var self = this; 
    //self.v = virtualField; 
    self.v = (function(){return self.v; this.clear = function(){self.v = '';}})() 
    self.v.prototype = function clear() { 
     self.v = ''; 
    } 
} 

我試過這些行。 我couldn`t找出定義這樣的的事兒。要這樣稱呼它

var temp = new theUploader('smart'); 
temp.v.clear(); 

有人正道的GUID我jsaon.but仍然在它的工作

回答

0

與此行中的問題(S):

self.v = (function(){return self.v; this.clear = function(){self.v = '';}})() 
如果您在多個行拆分出來0

...會更明顯:

self.v = (function(){ 
      return self.v; 
      this.clear = function(){ 
          self.v = ''; 
      } 
     })() 

這是一個立即調用的函數表達式返回它的第一線,所以它不會繼續執行this.clear = ...線。返回的值,self.v,將undefined在這一點上,這意味着self.v屬性分配該值也將是undefined,這意味着然後在這條線:

self.v.prototype = function clear() { 

...你會得到一個錯誤TypeError: Cannot set property 'prototype' of undefined

這是一個有點分不清你要不要給你的theUploader()功能混亂到底是什麼,但鑑於你說你希望能夠做到這一點:

var temp = new theUploader('smart'); 
temp.v.clear(); 

然後,你需要創建一個.v屬性,它本身具有.clear()方法的對象,所以:

function theUploader(virtualField) 
{ 
    var self = this; 
    self.v = {};        // create a v property that is an object 
    self.v.clear = function(){self.v = '';}; // add a method to v 
} 

...會做到這一點。或者你可以在對象字面直接定義clear功能:

 self.v = { 
     clear : function(){self.v = '';} 
    }; 

(無論哪種方式,它並沒有真正意義的我,調用self.v.clear()實際上有一個空字符串覆蓋.v屬性,但如果這就是你想這是你如何做到這一點。)

+0

thnanks.that是有幫助的。 – Ariyous

0
self.v.prototype = function clear() { 
    self.v = ''; 
} 

self.v.clear = function() { 
    self.v = ''; 
} 
+0

不幸的是,沒有working.i試過,但忘了提及一個 – Ariyous

相關問題