是什么让javascript变得如此奇妙
2016-04-27 23:46
471 查看
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)) })
相关文章推荐
- 学习js的点点滴滴记录
- cjson源码阅读有感
- 更改ejs模板引擎的后缀为html
- django 提示ImportError: cannot import name json_response
- javascript去掉空格
- JavaScript Observer Pattern
- 通过js看类似C#中的回掉
- POJO与JSON的序列化与反序列化
- 通过js看类似C#中的回掉
- 字符串与json之间的相互转化
- flash和js通过什么类如何交互?
- jstree的基本使用例子
- json小计
- Javascript 将json字符串解析成js 对象的四种方法
- js map
- javascript实现jsonp跨域访问
- js中运算符&& 和 || 的使用记录
- javascript json prase get key by index get value by index
- JavaScript API 设计原则
- 将JavaScript 插入网页的方法