6

I'm currently trying to get a better understanding of JavaScript and prototyping.

I wanted to add a function to the document but prototype is undefined on document.

This code:

document.prototype.writeLine = function(text){
    this.write(text);
    this.write("<br />");  
};

Generates this error:

// In FireFox
TypeError: document.prototype is undefined

// In Chrome
Uncaught TypeError: Cannot set property 'writeLine' of undefined 

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.

4

3 回答 3

9

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.

Update: Here is a snippet which works in IE9 because under IE9 HTMLDocument is 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");

于 2012-10-02T11:58:01.830 回答
1

The problem is that document is of type object and not function. In JavaScript you use functions as constructors like this:

function MyClass() {
    this.myProperty = "something";
}

You may create an instance of MyClass as follows:

var myInstance = new MyClass;
alert(myInstance.myProperty);

Every function also has a property called prototype which is an object. All the properties of the prototype are inherited my instances of the constructor function:

MyClass.prototype.displayProperty = function () {
    alert(this.myProperty);
};

myInstance.displayProperty();

In your case since document is the instance of a constructor and not the constructor itself, there's no property called prototype on it.

For more information about inheritance in JavaScript read this answer.

于 2012-10-02T12:10:10.630 回答
1

is very easy, document and Document are both different, document is the document of the window and Document is the interface of the document (thats comone from DOM), if your like add a new prototype for you use in your document you need add this but into Document like this:
window.Document.prototype.Sayhi = "Hello World" or Document.prototype.Sayhi = "Hello World" and now you can call this from you document like document.sayhi thats happen because you need Set the prototype on Interfaces if you like for example add a new prototype in your Object window your need Set it at Window interface like: Window.prototype.Saybye = "Bye Bro See You Later" and you can call the prototype in you window.Saybye remember, Window is an interface that contain window like Document and document****

于 2018-06-29T10:08:37.640 回答