javascript函数对象原型(prototype)

标签 javascript html

为什么点击图片时不调用原型(prototype)函数?

HTML 代码:--

    <!DOCTYPE html>
    <html style="height: 100%;">
    <head>
      <script type="text/javascript" src="tt.js"></script>
    </head>
    <body>

    <p>This example calls a function which performs a calculation, and returns the result:</p>

    <p id="demo"></p>

    <input type="image" src="http://t2.gstatic.com/images?q=tbn:ANd9GcSTcJA5J-LOj0HOP1ZMzdSQIsxwuguFdtlesHqzU15W8TXx232pFg" onclick="myFunction('Info clicked')"/>

   <script>
     var a = new myFunction();
     document.getElementById("demo").innerHTML = a.k;
    </script>

    </body>
    </html>

Java 脚本:--

function myFunction(l) {
    this.k = "hello";
    alert(this.k);

    var t = this.temp(l);
    alert(t);


}

myFunction.prototype.temp = function(a)
{
    alert(a);

    return 10;
}

如果我将 html 页面主体放入其中,它会起作用:--

<script>
var a = new myFunction();
document.getElementById("demo").innerHTML = a.k;
</script>

最佳答案

因为您是在构造函数上调用 this.temp() 而不是在它的实例上。

您需要使用new 创建一个实例。

new myFunction('Info clicked')

请注意,这没有意义。如果你想在构造函数运行时做一些事情,你应该将方法分配给构造函数而不是原型(prototype)。

关于javascript函数对象原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25306079/

相关文章:

javascript - 如何从链接中添加/删除类

javascript - 如何在 Javascript 中将数组值映射到对象内的数组?

jquery - 通过 jQuery 更改高度后如何对齐一组 div 元素的顶部?

html - Margin-top 没有按预期工作

javascript - 单击添加按钮绝对没有任何作用,我不知道为什么

html - 如何为div的背景颜色设置不透明度?

javascript - 如何在 JavaScript 对象中做 css

javascript - 使用react-hook-form的Controller组件不允许自定义Antd Select显示标签

javascript - Web 组件 (LIT) - Accordion 在打开其他组件时关闭

html - 在浏览器中显示 xml,没有警告消息