Adding the method to the facility through prototype
-
The code below shall designate a type object
Image
with prototype three new methods:protocol()
♪host()
andpathname()
♪
The fireFox browser is going well. Chrome makes the following mistake:Uncaught TypeError: document.i1.protocol is not a function
Accordingly, and other functions
document.i1.host
anddocument.i1.path
Not implemented.What's the problem and how do we solve it?
function pr() { a = this.src.split(':'); return a[0] + ':'; }
function ho() {
a = this.src.split(':');
path = a[1].split('/');
return path[2];
}function pa() {
path = this.src.split('/');
path[0] = '';
path[2] = '';
return path.join('/').split('///').join('/');
}Image.prototype.protocol = pr;
Image.prototype.host = ho;
Image.prototype.pathname = pa;document.write("<IMG NAME=i1 SRC='img1.jpg'><BR>");
document.write(document.i1.src + "<BR>");
document.write(document.i1.protocol() + "<BR>");
document.write(document.i1.host() + "<BR>");
document.write(document.i1.pathname() + "<BR>");
-
Received
<img>
(e.g. bydocument.getElementById('img')
ornew Image()
has a typeHTMLImageElement
♪ Accordingly, adding new methods is necessary in his prototype.Example:
function log(info) { document.body.innerHTML += info + "<br/>"; }
HTMLImageElement.prototype.protocol = function() {
log("Protocol is called");
};var img = document.getElementById('img');
log("Got image: " + img.constructor.name);
img.protocol();var newImage = new Image();
log("New image: " + newImage.constructor.name);
newImage.protocol();<img id='img' /><br/>