如何在不把方法放入对象内的情况下调用方法操作鸟类对象属性?
解决方案:将方法移至对象外部操作属性
你可以通过两种常见方式实现把方法放在对象外部来操作Bird实例的属性:
方式一:独立外部函数
直接编写独立函数,将目标bird对象作为参数传入,函数内部直接操作对象的属性。这种方式简单直观,每个函数专注单一操作:
// 外部函数:获取颜色 function getColor(bird) { return bird.color; } // 外部函数:设置颜色 function setColor(bird, newColor) { bird.color = newColor; } // 外部函数:添加栖息地 function addLocation(bird, newLocation) { bird.locations.push(newLocation); } // 外部函数:获取所有栖息地 function getLocations(bird) { return bird.locations; } // 原工厂函数,移除内部方法 function Bird(species, color, locations) { return { species: species, color: color, locations: locations }; } // 使用示例 const newBird = Bird('canary', 'red', ['newyork', 'spain']); console.log(newBird); console.log(getColor(newBird)); // 输出 red setColor(newBird, 'yellow'); console.log(getColor(newBird)); // 输出 yellow addLocation(newBird, 'france'); console.log(getLocations(newBird)); // 输出 ['newyork', 'spain', 'france']
方式二:利用原型共享方法
如果希望方法能通过对象的this调用(和原来的调用方式更接近),可以让工厂函数返回的对象继承自Bird.prototype,把方法挂载到原型上,这样所有Bird实例共享这些方法,避免重复创建:
// 原型上的方法 Bird.prototype.getColor = function() { return this.color; }; Bird.prototype.setColor = function(newColor) { this.color = newColor; }; Bird.prototype.addLocation = function(newLocation) { this.locations.push(newLocation); }; Bird.prototype.getLocations = function() { return this.locations; }; // 修改工厂函数,让返回的对象继承原型 function Bird(species, color, locations) { const birdObject = Object.create(Bird.prototype); // 继承原型方法 birdObject.species = species; birdObject.color = color; birdObject.locations = locations; return birdObject; } // 使用示例和原来一致 const newBird = Bird('canary', 'red', ['newyork', 'spain']); console.log(newBird); console.log(newBird.getColor()); // 输出 red newBird.setColor('yellow'); console.log(newBird.getColor()); // 输出 yellow newBird.addLocation('france'); console.log(newBird.getLocations()); // 输出 ['newyork', 'spain', 'france']
两种方式的区别
- 独立函数:调用时需要显式传入bird对象,适合简单场景,无需关注原型继承。
- 原型方法:调用方式和你原来的代码完全一致,利用
this指向当前对象,适合需要多个实例共享方法、减少内存开销的场景。
内容的提问来源于stack exchange,提问作者kidnoj
相关产品推荐
相关产品推荐

