包装类练习
var str = 'aaa';
str += 1;
var test = typeof (str);
if (test.length == 6) {
test.newproperty = 'string';
}
console.log(test.newproperty) // undefined
运行时:
var str = 'aaa';
str += 1; // 'aaa1'
var test = typeof (str); // 'string'
if (test.length == 6) {
test.newproperty = 'string';
// 上面一行代码相当于运行下面三行
// var obj = new Object(test); ------------code1
// obj.newproperty = 'string';
// 摧毁obj(其实test并没有什么改变)
}
console.log(test.newproperty) // undefined
闭包
function outer() {
var arr = new Array();
for (var i = 0; i < 2; i++) {
arr[i] = function () {
return i;
}
}
return arr;
}
var fn = outer();
console.log(fn[0]()); // 2
console.log(fn[1]()); // 2
修改上面的代码输出0,1(使用立即执行函数)
function outer() {
var arr = new Array();
for (var i = 0; i < 2; i++) {
arr[i] = function (x) {
return function(){
return x;
}
}(i);
}
return arr;
}
var fn = outer();
console.log(fn[0]()); // 0
console.log(fn[1]()); // 1
this
var name = 'The window';
var object = {
name: 'my object',
getNameFunc: function(){
return function(){
return this.name;
};
},
getNameFunc2: function(){
return this.name;
}
}
console.log(object.getNameFunc()()); // The window
console.log(object.getNameFunc2()); // my object