我目前正在尝试更好地理解JavaScript和原型设计。
我想向document
添加一个函数,但prototype
document
上未定义。
此代码:
document.prototype.writeLine = function(text){
this.write(text);
this.write("<br />");
};
生成此错误:
// In FireFox
TypeError: document.prototype is undefined
// In Chrome
Uncaught TypeError: Cannot set property 'writeLine' of undefined
如何扩展document
对象以便能够调用类似于document.WriteLine('MyText')
的东西?
这是我正在使用的小提琴。
我更新了你的小提琴。您遇到的问题是document
对象是HTMLDocument
对象类型的实例。实例本身没有原型,但HTMLDocument
有。
更新:这是一个在IE9中有效的代码片段,因为在IE9下HTMLDocument
是undefined
。
if (typeof HTMLDocument !== 'undefined') {
HTMLDocument.prototype.writeLine = function(text){
this.write(text);
this.write("<br />");
};
} else {
Document.prototype.writeLine = function(text){
this.write(text);
this.write("<br />");
};
}
document.writeLine("Line 1");
document.writeLine("Line 2");
问题是document
属于 object
型而不是 function
型。在 JavaScript 中,你使用函数作为构造函数,如下所示:
function MyClass() {
this.myProperty = "something";
}
您可以按如下方式创建MyClass
实例:
var myInstance = new MyClass;
alert(myInstance.myProperty);
每个函数还具有一个名为 prototype
的属性,它是一个对象。原型的所有属性都继承了构造函数的实例:
MyClass.prototype.displayProperty = function () {
alert(this.myProperty);
};
myInstance.displayProperty();
在您的情况下,由于document
是构造函数的实例而不是构造函数本身,因此其上没有名为 prototype
的属性。
有关 JavaScript 中继承的更多信息,请阅读此答案。
,文档和文档都是不同的,文档是窗口的文档,文档是文档的界面(这是DOM的comone),如果您喜欢添加一个新原型供您在文档中使用,则需要添加这个,但像这样添加到文档中:
窗。Document.prototype.Sayhi = "Hello World"或 Document.prototype.Sayhi = "Hello World"现在你可以从你的文档中调用它,就像文档.赛希发生这种情况是因为您需要在接口上设置原型,例如在对象窗口中添加新原型,您需要在窗口界面上设置它,例如:Window.prototype.Saybye = "Bye Bro See You Later"您可以在窗口中调用原型。赛拜请记住,窗口是一个包含类似文档和文档的窗口的界面****