具有对象构造函数创建的方法的对象:
function objectexample(name) {
this.name = name;
this.create = function(){
var obj = document.createElement('div');
obj.id = this.name;
parent = document.getElementsByTagName("body")[0];
parent.appendChild(obj);
}
this.showalert = function(){
alert("alert");
}
}
现在我创建对象:
var obj1 = new objectexample("new1");
如何为此对象运行方法 .create,但不使用变量 obj1,我想使用 ID 获取对象,例如:
document.getElementById("new1").showalert();
这可能吗?
最佳答案
基本上,是的,这是可能的
但是,您需要该元素包含对创建它的对象的引用。
在下面的演示中:
- 在构造
new
obj1
时,我们定义了3个属性:- 它的
名称
。 - 一个
create()
方法,当被调用时会创建一个元素。 - 一个
showAlert()
方法,调用时会输出一些数据。
- 它的
- 在调用
create()
之前调用showAlert()
时,我们会得到有关该对象的所有可用数据,但不会得到有关尚未创建的元素的任何数据。 - 当调用
create()
时,我们创建元素,并将creation
定义为对象的属性,元素作为其值。 - 然后我们将
creator
定义为元素的属性,其值为this
(创建元素的对象)。 - 现在对象 (
creator
) 有一个名为creation
的子元素,该元素有一个creator
及其所有属性,包括它的方法。
换句话说,如果 new
对象产生了一个元素,该元素将采用其创建者的属性,并且创建者会紧紧握住它的 child 的手。
function ObjectExample( name ) {
this.name = name;
this.create = function() {
this.creation = document.createElement( "div" );
this.creation.id = name;
this.creation.creator = this;
document.body.appendChild( this.creation );
}
this.showAlert = function() {
// alert( "Alert!" ); // simpler for demo to use console
console.log( this.name );
console.log( this.creation );
return this.creation;
}
}
let obj1 = new ObjectExample( "new1" );
if ( !obj1.showAlert() ) {
obj1.create();
}
document.getElementById( "new1" ).creator.showAlert();
关于javascript - 是否可以使用对象的 ID 运行对象方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45438831/