是什么让javascript变得如此奇妙

What Makes Javascript Weird...and AWESOME
-> First Class Functions
-> Event-Driven Evironment
-> Closures
-> Scope
-> Context

scope === variable access
context === this

First Class functions(回调函数)

function add(first,second,callback){
	console.log(first+second);
	if(callback){
		callback();
	}
}

function logDone(){
	console.log('done');
}

add(2,3,logDone);
add(4,5);

function handleClick(){
	//something smart
}
$('#myDiv').click(handleClick);

Event-Driven Evironment(事件绑定,事件驱动)

var a = 1;
console.log('up');
jQuery(document).ready(function(){
	jQuery('button').on('click',function(){
		alert(a);
	})
})

Closures(闭包)

jQuery(document).ready(function(){
	var a = 1;
	jQuery('button').on('click',function(){
		alert(a++);
	})
})

scope(作用域)

//scope ==== variable access
//首先在自己区域找,如果没有定义,影响的就是父亲节点的		
var a = 1;
function foo(){
	var b = 2;
}
foo();
console.log(b);
var a = 1;

function foo(){
	//定义了,自己看着办
	var a = 2;
	console.log(a);
}

function bar(){
	//没有定义,找父亲,影响父亲
	a = 3;
	console.log(a);
}

foo();
bar();
console.log(a);

//233

context(执行上下文对象)

context === this

this===window;
var a = 1;
console.log(window.a);//1
console.log(this.a);//1
console.log(window === this);


function foo(){
	console.log(this);
}
foo();//Window test.html

var obj = {
	foo : function(one, two, three){
		console.log(one);
		console.log(this === window);//谁调用this指向谁
	}
}
obj.foo();//false

//call apply bind 扩充作用域,对象不需要和方法有任何耦合
obj.foo.call(window,1,2,3);//true
obj.foo.apply(window,[1,2,3]);//true
var myBoundFoo = obj.foo.bind(window);
myBoundFoo();//true
obj.foo();//false

$('#openDiv').on('click',function(){
	$('#div1').sideToggle(200,function(){
		$(this).toggleClass('active');
	}.bind(this))
})
posted @ 2016-04-27 23:46  IT-caijw  阅读(185)  评论(0编辑  收藏  举报