【发布时间】:2014-12-01 08:03:36
【问题描述】:
给定:
function testfunc(i) {
this.foo = function() {
i = 2;
console.log("testfunc.foo before bar: " + i);
this.bar();
console.log("testfunc.foo after bar: " + i);
};
this.bar = function() {
i = 3;
console.log("testfunc.bar: " + i);
};
}
var testvar = {
foo: function() {
i = 4;
console.log("testvar.foo before bar: " + i);
this.bar();
console.log("testvar.foo after bar: " + i);
},
bar: function() {
i = 5;
console.log("testvarbar: " + i);
}
};
var a = new testfunc();
var b = Object.create(testvar);
i = 1;
a.foo();
console.log("main: " + i);
b.foo();
console.log("main: " + i);
结果是:
"testfunc.foo before bar: 2" scope.html:37
"testfunc.bar: 3" scope.html:44
“bar 后的testfunc.foo:3” scope.html:39
"main:1" scope.html:66
"testvar.foo before bar: 4" scope.html:51
"testvarbar: 5" scope.html:58
“bar 后的testvar.foo:5” scope.html:53
"main: 5" scope.html:68
是否应该像这样,i 变量在 javascript 对象中从一个方法/函数继承到另一个方法/函数?这是否意味着在 javascript 中实例化对象的唯一安全方法是在函数上使用“new”,还是我完全忽略了这一点?
【问题讨论】: