js回调函数callback传值与赋值

1.简单的回调

function demo(callback){
    callback(1)
}
demo(function(e) {
    console.log(e)  //1
})

2. 回调赋值

function demo(callback){
    var opts = {
        ids: [1,2,3,4],
        list: ['ho','yang','lee','chan']
    }
    callback(opts)
}
demo(function(e) {
    console.log(e) //{"ids":[1,2,3,4],"list":["ho","yang","lee","chan"]}
})

3. 回调传值与赋值

function demo(originalOpts,callback){
    var opts = {
        ids: originalOpts.ids.concat([5,6,7]),
        list: originalOpts.list.concat(['xu','zhu','fu'])
    }
    callback(opts)
}
demo({
	ids: [1,2,3,4],
	list: ['ho','yang','lee','chan']
	},function(e) {
    console.log(e)  //{"ids":[1,2,3,4,5,6,7],"list":["ho","yang","lee","chan","xu","zhu","fu"]}
})

 

你可能感兴趣的:(web前端)