如何扩展文档对象? [英] How can I extend the document object?
问题描述
我目前正在努力更好地理解JavaScript和原型设计。
I'm currently trying to get a better understanding of JavaScript and prototyping.
我想在文档中添加一个函数
但原型
在文件
上未定义。
此代码:
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.WriteLine('MyText')
?
How can I extend the document
object to be able to call something similar to document.WriteLine('MyText')
?
这是 小提琴 我正在使用。
Here is the Fiddle I'm working with.
推荐答案
我更新了你的小提琴。您遇到的问题是 document
object是 HTMLDocument
对象类型的一个实例。 实例本身没有原型,但 HTMLDocument
可以。
I updated your fiddle. The problem you were having is that document
object is an instance of the HTMLDocument
object type. The instance itself doesn't have a prototype, however the HTMLDocument
does.
更新:这是一个小提琴更新,可在IE9中使用,因为在IE9下 HTMLDocument
是 undefined
。
Update: Here is a fiddle update which works in IE9 because under IE9 HTMLDocument
is undefined
.
这篇关于如何扩展文档对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!