1.Scope
(function() {
var a = b = 5;
})();
console.log(b);
Ans: 5 , 因為 b 沒用 var , 等同於 var a = window.b = 5 ;
(function() {
'use strict';
var a = window.b = 5;
})();
console.log(b);
2: Create “native” methods
console.log('hello'.repeatify(3));
Ans:
String.prototype.repeatify = String.prototype.repeatify || function(times) {
var str = '';
for (var i = 0; i < times; i++) {
str += this;
}
return str;
};
3: Hoisting
function test() {
console.log(a);
console.log(foo());
var a = 1;
function foo() {
return 2;
}
}
test();
Ans: undefined and 2.
function test() {
var a;
function foo() {
return 2;
}
console.log(a);
console.log(foo());
a = 1;
}
test();
4: How this work in JavaScript
var fullname = 'John Doe';
var obj = {
fullname: 'Colin Ihrig',
prop: {
fullname: 'Aurelio De Rosa',
getFullname: function() {
return this.fullname;
}
}
};
console.log(obj.prop.getFullname());
var test = obj.prop.getFullname;
console.log(test());
Ans:
Aurelio De Rosa
and John Doe
.因為第二種方式, this 被指到 window 了.
5: Use call() and apply()
Ans:
console.log(test.call(obj.prop));
沒有留言:
張貼留言