【问题标题】:Making a custom method that changes an objects property制作更改对象属性的自定义方法
【发布时间】:2011-09-19 18:45:45
【问题描述】:

我是自定义对象的新手,但发现它们非常有用,特别是因为从长远来看可以减少大量代码编写。

我正在使用一种特定的算法来创建一个克隆元素,并使用一种方法来创建一个基于克隆元素的某些属性的新唯一 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;,但它似乎不起作用。知道我做错了什么吗?

抱歉,我将其发布在此处是一个错误,但我已修复它,这就是它的实际外观,但它仍然无法正常工作。

【问题讨论】:

  • 不应该var nwID = clonedElement.theID;var nwID = clonedElement.theID();
  • 抱歉,我修好了,但括号还是不行。

标签: javascript methods properties


【解决方案1】:

theID是一个函数,所以需要调用它:

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
}

【讨论】:

  • 对不起,它确实有参数的区域,但它仍然不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 1970-01-01
  • 2012-07-06
  • 1970-01-01
  • 1970-01-01
  • 2022-06-12
相关资源
最近更新 更多