昨天遇到的一个问题:对于两个普通的对象a,bvar a = { foo:1, methodA:function(){ console.log(this.foo);
}
}var b = { bar:2, methodB: function(){ console.log(this.bar);
}
}可以不考虑执行环境的兼容性,实现下面要求:1 执行a.methodA()输出1;2.执行a.methodB()输出2;3.执行b.bar=3;a.methodB()输出3上面的就是题目,首先想到的就是继承,a继承b,可以直接调用b的methodB方法。在题目的基础上,我会这么实现的:function A(){ this.foo = foo; this.methodA = function(){ console.log(this.foo);
}
B.call(this) //实现继承
}function B(){ this.bar = bar; this.methodB = function(){ console.log(this.bar);
}
} var a = new A(); var b = new B();执行下面的代码:a.methodA() //输出1;a.methodB() //输出2;b.bar=3;a.methodB() //仍输出2很显然不符合要求。求大神告知产生的原因和解决的方法。 难道是我一开始就理解的不正确吗?
添加回答
举报
0/150
提交
取消