Vanilla JS下如何从另一构造函数访问私有方法中的变量
解决方案
核心问题是ColourPalette私有方法colourClick里的c是局部变量,外部无法直接访问。要解决这个问题,需要在ColourPalette中通过闭包保存选中颜色的状态,并提供公共方法供外部获取该状态。
步骤1:修改ColourPalette,暴露选中颜色的访问接口
把选中的颜色存在闭包变量中,新增一个公共方法返回这个颜色:
function ColourPalette() { // 闭包变量保存选中的颜色,作为私有状态 let selectedColour = "#000000"; // 设置默认颜色,避免初始值为undefined // 私有方法:处理颜色点击 function colourClick() { // 这里假设你通过按钮背景色获取颜色,根据实际逻辑调整 selectedColour = this.style.backgroundColor; console.log("选中颜色:", selectedColour); // 可选:验证颜色更新 } // 公共方法:供外部获取当前选中的颜色 this.getSelectedColour = function() { return selectedColour; }; // --- 初始化颜色面板(示例代码)--- const colours = ["#ff0000", "#00ff00", "#0000ff", "#000000"]; colours.forEach(col => { const btn = document.createElement("button"); btn.style.backgroundColor = col; btn.style.width = "30px"; btn.style.height = "30px"; btn.addEventListener("click", colourClick); document.body.appendChild(btn); }); }
步骤2:在CircleTool中调用公共方法获取颜色
在CircleTool中,当需要填充时,调用传入的ColourPalette实例的getSelectedColour()方法即可:
function CircleTool(colourPalette) { this.fillEnabled = true; this.colourPalette = colourPalette; // 切换填充状态的方法 this.toggleFill = function() { this.fillEnabled = !this.fillEnabled; }; // P5.js绘制圆形的方法 this.draw = function(x, y, diameter) { if (this.fillEnabled) { // 获取选中的颜色并设置填充 let fillCol = this.colourPalette.getSelectedColour(); fill(fillCol); } else { noFill(); } stroke("#000"); // 保持描边(可根据需求调整) ellipse(x, y, diameter, diameter); }; }
步骤3:实例化并使用
在P5.js的setup函数中初始化两个实例,把ColourPalette传入CircleTool:
let colourPalette; let circleTool; function setup() { createCanvas(800, 600); colourPalette = new ColourPalette(); circleTool = new CircleTool(colourPalette); // 添加填充切换按钮(示例) const toggleBtn = document.createElement("button"); toggleBtn.textContent = "切换填充"; toggleBtn.style.marginLeft = "10px"; toggleBtn.addEventListener("click", () => circleTool.toggleFill()); document.body.appendChild(toggleBtn); } function mouseDragged() { // 拖拽鼠标绘制圆形,直径设为50(可调整) circleTool.draw(mouseX, mouseY, 50); }
关键说明
- 闭包变量
selectedColour仅在ColourPalette内部可修改,通过getSelectedColour暴露读取权限,符合封装思想。 - 如果你的颜色获取逻辑是用P5.js的
color()函数,只需把selectedColour存为P5.js的颜色对象即可,比如selectedColour = color(this.style.backgroundColor)。
内容的提问来源于stack exchange,提问作者AlexSt
相关产品推荐
相关产品推荐

