我完全同意鲍里斯......你应该在这里搜索更多细节(https://www.google.com/search?q=javascript+prototype+chain)但基本上如果你想浏览 DOM 对象中的元素,你只需要像下面这样:
function exploreElement(element){
contentToString = "";
for (var i in element){
contentToString += i + " : " + element[i] + "<br />";
}
document.write(contentToString);
}
exploreElement(document);
原型和原型是完全不同的东西......
如果您有这样的构造函数:
function SomeObject(){
this.__proto__.id = "instance_default_name";
SomeObject.id = "SomeObject";
// __proto__ HERE to access the prototype!!!
}
然后,您可以通过原型向此构造函数添加方法(我假设您在文档中有一个 id 为“myInstance”的空 div 和另一个 id 为“test”的 div):
SomeObject.prototype.log = function(something){
document.getElementById("myInstance").innerHTML += something + "<br />";
}
添加一些用于测试目的的方法:
SomeObject.prototype.setId = function(id){
this.id = id;
}
SomeObject.prototype.getId = function(){
return this.id;
}
SomeObject.prototype.getClassName = function(){
return SomeObject.id;
}
然后,您可以使用 new 运算符实例化 SomeObject 并进行如下测试:
myInstance = new SomeObject();
myInstance.setId("instance_1");
aDivElement = document.getElementById("test");
aDivElement.style.backgroundColor = "rgb(180,150,120)";
myInstance.log("p1 = " + aDivElement);
// [object HTMLDivElement]
myInstance.log("p1 backgroundColor = " + (aDivElement.style.backgroundColor));
myInstance.log("myInstance = " + myInstance);
// [object Object] an instance of SomeObject
myInstance.log("myInstance.constructor = " + myInstance.constructor);
// function SomeObject() { this.__proto__.id = "instance_default_name"; SomeObject.id = "SomeObject"; }
myInstance.log("myInstance.constructor.prototype = " + myInstance.constructor.prototype);
// .prototype WHEN CALLED by the instance NOT __proto__
// The constructor of myInstance is SomeObject and the prototype of SomeObject is the prototype of all instances of SomeObject
myInstance.log("myInstance.id = " + myInstance.getId());
// id for the instance of SomeObject that you have instanciated
myInstance.log("SomeObject.prototype.id = " + SomeObject.prototype.getId());
// id by default of the prototype
myInstance.log("myInstance.constructor.prototype.id = " + myInstance.constructor.prototype.getId());
// id by default of the prototype
myInstance.log("myInstance.getClassName() = " + myInstance.getClassName());
// myInstance.getClassName() = SomeObject
我不知道这是否对您有所帮助,但我希望这对您的搜索有所帮助。此致。尼古拉斯