gpt4 book ai didi

javascript - JS 几个函数通过原型(prototype)

转载 作者:行者123 更新时间:2023-11-30 13:05:32 24 4
gpt4 key购买 nike

我是 JS 新手。例如,如果我想将 2 个函数分配给构造函数,我是否必须通过原型(prototype)调用函数声明两次?

function Shape(x, y) {
this.x= x;
this.y= y;
}



Shape.prototype.foo= function() {

return ...;
};

Shape.prototype.bar= function() {

return ...;
};

最佳答案

如果我没理解错的话,像这样的东西会起作用:

function Shape(x, y) {
this.x= x;
this.y= y;
}

Shape.prototype = {
constructor: Shape,
foo: function() {
return ...;
},
bar: function() {
return ...;
}
}

http://jsfiddle.net/Yc4V4/

关于javascript - JS 几个函数通过原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15844100/

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