一、
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
console.log(object.getNameFunc()()); // 'The window'
二、
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
var that = this;
return function(){
return that.name;
};
}
};
console.log(object.getNameFunc()()); // 'My Object'
三、
var fnArr = [];
for (var i = 0; i < 10; i ++) {
fnArr[i] = function(){
return i
};
}
console.log( fnArr[3]() ) // 输出10
改造后,输出3
第一种方法:
var fnArr = []
for (var i = 0; i < 10; i ++) {
fnArr[i] = (function(j){
return function(){
return j
}
})(i)
}
console.log( fnArr[3]() ) // 3
第二种方法:
var fnArr = []
for (var i = 0; i < 10; i ++) {
(function(i){
fnArr[i] = function(){
return i
}
})(i)
}
console.log( fnArr[3]() ) // 3
第三种方法:let是声明一个块级作用域的本地变量
var fnArr = []
for (let i = 0; i < 10; i ++) {
fnArr[i] = function(){
return i
}
}
console.log( fnArr[3]() ) // 3
四、封装一个Car对象
var Car = (function(){
var speed = 0;
function set(s){
speed = s
};
function get(){
return speed
};
function speedUp(){
speed++
};
function speedDown(){
speed--
};
return {
set: set,
get: get,
speedUp: speedUp,
speedDown: speedDown
};
})()
Car.set(30)
Car.get() //30
Car.speedUp()
Car.get() //31
Car.speedDown()
Car.get() //30
五、
for(var i=0; i<5; i++){
setTimeout(function(){
console.log('delayer:' + i )
}, 0)
}
//输出五次 5
改造后,连续输出 0,1,2,3,4
for(var i=0; i<5; i++){
(function(j){
setTimeout(function(){
console.log('delayer:' + j )
}, 0)
})(i)
}
或者
for(var i=0; i<5; i++){
setTimeout((function(j){
return function(){
console.log('delayer:' + j )
}
}(i)), 0)
}
六、
function makeCounter() {
var count = 0
return function() {
return count++
};
}
var counter = makeCounter();
var counter2 = makeCounter();
console.log( counter() ) // 0
console.log( counter() ) // 1
console.log( counter2() ) // 0
console.log( counter2() ) // 1
七、数组按姓名、年纪、任意字段排序
var users = [
{ name: "John", age: 20, company: "Baidu" },
{ name: "Pete", age: 18, company: "Alibaba" },
{ name: "Ann", age: 19, company: "Tecent" }
]
function byField(field){
return function(user1, user2){
return user1[field] > user2[field]
}
}
users.sort(byField('name'))
users.sort(byField('age'))
users.sort(byField('company'))
八、 sum 函数
function sum(a) {
return function(b) {
return a + b
}
}
console.log( sum(1)(2) ) // 3
console.log( sum(5)(-1) ) // 4
九、实现 console.log(sum(1)(2)...(98)(99)) // 5050
function sum(a) {
function s(b) {
a += b
return s
}
s.toString = function(){return a}
return s
}
网友评论