gpt4 book ai didi

javascript - 调用所有对象的函数

转载 作者:行者123 更新时间:2023-12-02 19:10:41 27 4
gpt4 key购买 nike

我试图在每次鼠标单击时调用所有按钮对象的方法,但我一点也不熟悉 javascript 原型(prototype)的工作原理,非常感谢您的帮助。这是我到目前为止所拥有的。

var button1 = new button(200, 200, 150, 150, "testFunc();"); 
function button(x,y,width,height, func) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.func = func;

}

button.prototype.click = function(clickx, clicky) {
eval(this.func)
console.log("Clicked button at" + this.x + " " + clicky);
if (clickx > this.x && (clickx + width) < this.x) {
if (clicky > this.y && (clicky + height) < this.y) {

this.func(); //Call the button's function
}
}
}

function onClick(x, y) {
button.prototype.click.call(x, y);
}

我基本上希望每个按钮对象都使用单击的 xy 坐标来检查它是否被单击。当然这应该可以用 javascript 实现吗?

最佳答案

好的,有几件事。

  1. 构造函数应始终以大写字母开头。 按钮不是按钮
  2. 函数是对象,您可以直接传入一个函数,而无需使用 eval 来执行任何操作。
  3. 如果要对按钮列表进行操作,则需要按钮列表。原型(prototype)中的函数与所有实例共享,但您无法从原型(prototype)中获取所有实例。您需要自己维护该列表。数组非常适合列表。
<小时/>
// Constructor! capitalized!
function Button(x, y, width, height, func) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.func = func;
}

// Each constructed Button will have a click() method.
Button.prototype.click = function(clickx, clicky) {
console.log("Clicked button at" + this.x + " " + clicky);
if (clickx > this.x && (clickx + width) < this.x) {
if (clicky > this.y && (clicky + height) < this.y) {
this.func(); //Call the button's function
}
}
}

// Passed as the function to execute in this not very exciting example.
function testFunc() {
console.log('called testFunc()!')
}

// Make a bunch of buttons, save them in an array.
// Note how we actually pass a function object as the last argument.
// Note how the last argument IS NOT a string.
var buttons = [
new Button(100, 100, 150, 150, testFunc),
new Button(250, 250, 150, 150, testFunc),
new Button(400, 400, 150, 150, testFunc)
];

// called by something else that passes x and y
function onClick(x, y) {
// tell each button we had a click, and pass in x and y to see
// if it should handle it.
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
button.click(x, y);
}
}

关于javascript - 调用所有对象的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13773027/

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