gpt4 book ai didi

javascript - 使用原型(prototype)调用方法

转载 作者:行者123 更新时间:2023-11-30 08:08:30 28 4
gpt4 key购买 nike

<script>     
var Kevin = function(){
this.name = 'kevin'
}
Kevin.prototype.getKevin = function(){
alert(this.name);
}
Kevin.prototype.getKevin();

function John(){
this.name = 'john'
}
John.getStaticJohn = function(){
alert(this.name);
}

John.prototype.getJohn();
John.getStaticJohn();

</script>
  1. 为什么我在调用时在这两种情况下都得到 undefined使用原型(prototype)的方法。
  2. 当我尝试调用 John 类中的静态方法时,它打印出完美输出。

最佳答案

如果你想从构造函数中调用方法,你需要创建一个匿名实例:

(new Kevin).getKevin(); // or new Kevin().getKevin()

关于javascript - 使用原型(prototype)调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14087030/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com