zoukankan      html  css  js  c++  java
  • 是什么让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))
    })
    
  • 相关阅读:
    GoF23:工厂模式(Factory)
    CSS
    HTML
    JSP基础学习
    JSTL标签
    Jsoup
    Centos7下tomcat关闭异常问题
    剑指Offer_#18_删除链表的节点
    剑指Offer_#17_打印从1到最大的n位数
    剑指Offer_#16_数值的整数次方
  • 原文地址:https://www.cnblogs.com/caijw/p/5440968.html
Copyright © 2011-2022 走看看