【发布时间】:2017-07-08 23:23:30
【问题描述】:
尊敬的社区和 Javascript 向导,
我遇到了我无法理解的行为。
我的意图是创建一个模块,它模拟私有变量并控制对象的创建。
我希望以下示例说明我想要什么以及我的问题是什么。
const ex = (() => {
// Creating the constructor for points
function Point() {
let x;
let y;
// I think using prototype is a good idea, because it can be expected that a lot of points are created. So I do not waste memory with a lot of function duplications.
Point.prototype.setX = xValue => {
x = xValue;
}
Point.prototype.setY = yValue => {
y = yValue;
}
Point.prototype.getY = () => {
return y;
}
}
// Returning an interface to create points
// but hide their properties.
return {createPoint: (x,y) => {
let point = new Point();
point.setX(x);
point.setY(y);
return point;
}}
})();
p1 = ex.createPoint(1,2);
console.log(p1.getY()); // Result is '2' as expected
p2 = ex.createPoint(3,4);
console.log(p2.getY()); // Result is '4' as expected
console.log(p1.getY()); // Result is '4'..Wait...'4' what? Why?!
我认为明显的来源是我对范围的理解…… 我的假设是,如果我创建一个函数作为原型属性: 1. 该功能对所创建种类的所有对象可见。 2.原型函数作用于使用它的对象的作用域。
根据我的结果,我怀疑数字 2 是否正确。
所以我又试了一次,将属性和方法直接分配给新创建的对象(我希望我这样做了……)
const ex = (() => {
// Creating the constructor for points
function Point() {
this.x;
this.y;
// I think using prototype is a good idea, because it can be expected that a lot of points are created. So I do not waste memory with a lot of function duplications.
this.setX = xValue => {
x = xValue;
}
this.setY = yValue => {
y = yValue;
}
this.getY = () => {
return y;
}
}
// Returning an interface to create points
// but hide their properties.
return {createPoint: (x,y) => {
let point = new Point();
point.setX(x);
point.setY(y);
return point;
}}
})();
p1 = ex.createPoint(1,2);
console.log(p1.getY()); // Result is '2' as expected
p2 = ex.createPoint(3,4);
console.log(p2.getY()); // Result is '4' as expected
console.log(p1.getY()); // Result is '4'..Wait...'4' what? Why?!
但结果没有改变,我无法理解这种行为。 在重读了我的 js 圣经中关于闭包和原型的章节之后,我不知道在哪里可以搜索或找到帮助,而不是问你。
如果您能向我指出我的错误并解释我的代码出了什么问题,我会很高兴。
亲切的问候
吉姆
【问题讨论】:
标签: javascript object module prototypejs