简体   繁体   中英

Object.prototype using 'this'

This might be basic, it might not be possible, I might be misunderstanding totally but I am a beginner trying to understand how adding methods to objects using Object.prototype works.

The best way to explain my question is to show firstly show the following:

Object.prototype.printHTML = function() {
    alert(this.innerHTML);
};

this seems to refer simply to Object.prototype.printHTML (alerting the HTML of exactly what is after the = sign in the above.

My question is , can you refer directly to the Object used?

so, the below would alert "Test Paragraph":

<body>
<p id='test'>Test Paragraph</p>

<script>
Object.prototype.printHTML = function() {
    alert(this.innerHTML);
};

document.getElementById("test").printHTML; //this would alert "Test Paragraph"
//currently alerts "function() {alert(this.innerHTML);}
</script>
</body>

I understand this example is pointless (because document.getElementById("test").innerHTML; gives me exactly what I would need for this) but I am just trying to understand creating methods using Object.prototype and I cannot figure out how to access the Object the method is being run on.

Thanks

You are really close, instead do this

<body>
<p id='test'>Test Paragraph</p>

<script>
Object.prototype.printHTML = function() {
    alert(this.innerHTML);
};

document.getElementById("test").printHTML(); //<--- HERE WE ADD THE PARENTHESIS
//currently alerts "function() {alert(this.innerHTML);}
</script>
</body>

You were accessing printHTML as a property rather and a function and executing it. Hence why you got the function as text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM