【问题标题】:Object.prototype using 'this'Object.prototype 使用 'this'
【发布时间】:2016-05-15 10:21:28
【问题描述】:

这可能是基本的,可能是不可能的,我可能完全误解了,但我是一个初学者,试图了解如何使用 Object.prototype 向对象添加方法。

解释我的问题的最佳方式是首先显示以下内容:

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

this 似乎只是指 Object.prototype.printHTML(提醒 HTML 上面的 = 符号之后的确切内容。

我的问题是,可以直接参考使用的Object吗?

所以,下面会提醒“测试段落”:

<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>

我知道这个例子是没有意义的(因为document.getElementById("test").innerHTML; 给了我我所需要的)但我只是想了解使用 Object.prototype 创建方法,我不知道如何访问该方法的对象正在运行。

谢谢

【问题讨论】:

  • 简单,把document.getElementById("test").printHTML改成document.getElementById("test").printHTML()
  • @CallumLinington 谢谢,我是多么的初学者!
  • 如果我有帮助,请接受答案:)
  • 对不起,请回来。我试着马上接受,但它不允许。现在完成,再次感谢。

标签: javascript object methods prototype


【解决方案1】:

你真的很亲近,不如这样做

<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>

您将printHTML 作为属性而不是函数访问并执行它。因此,为什么您将功能作为文本。

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 2013-05-24
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    相关资源
    最近更新 更多