我是新來的自定義對象,但發現它們非常有用,特別是因爲從長遠來看減少了大量的代碼編寫。製作更改對象屬性的自定義方法
我正在使用特定算法創建一個克隆元素,並使用一種方法根據克隆元素的某些屬性創建新的唯一ID。這是它現在看起來像:
Element.prototype.theID = theID;
function theID(){
//this.makeNewID code
//code that builds a new ID and stores it in a variable called nwID
return nwID
}
function buildClone(cloneThis){
//builds a clone out of the specified cloneThis element and stores it in a variable
//called clonedElement
var nwID = clonedElement.theID;//determines a new ID
clonedElement.setAttribute('id', nwID);//asignes the ID to the element.
}
buildClone()函數的最後兩行是我想要避免的。我希望方法將新的id分配給方法中的指定元素,而不是僅僅返回一個新的ID。
這是我想出了
Element.prototype.theID = theID;
function theID(){
//this.makeNewID code
//code that builds a new ID and stores it in a variable called nwID
this.setAttribute('id', nwID);//asignes the ID to the element.
}
function buildClone(cloneThis){
//builds a clone out of the specified cloneThis element and stores it in a variable
//called clonedElement
clonedElement.theID();//determines a new ID
}
這種新的方式,我嘗試它不工作,我自己也嘗試return clonedElement.theID;
,它似乎並沒有工作。任何想法我做錯了什麼?
我很抱歉,這是我在這裏發佈的一個錯誤,但我修復了它,這是它實際上的樣子,它仍然不起作用。
不應'變種NWID = clonedElement.theID;'是'變種NWID = clonedElement.theID();'? – epascarello
對不起,我修正了它,但它仍然不支持括號。 –