js函数和闭包

作用域

函数作用域

  • 在函数中,无论变量、函数声明先后,都会在调用时优先选择

块级作用域

  • js中不存在块级作用域,局部变量作用域并不会局限于块级

      {
          for(var i=0;i<10;i++){
              //...    
          }
          //这里i值为10
      }
    
  • 但let声明的变量可实现块级作用域

闭包

  • 闭包函数返回值指向一个函数引用,所以闭包函数所赋给的变量不销毁的情况下,其对应的函数对象就不销毁,而且内部处在作用域链上的局部变量也就不会消失,达到具有状态的函数效果

回调

  • 回调函数没有状态,可以用bind(只绑定不立即执行,区别于call、apply)确定内部this引用

      //回调函数
      var emitter={ 
          callbacks:[],
          register:function(fn){
              this.callbacks.push(fn);
          },
          onOpen:function(){
                  for each(var f in this.callbacks){
              f();
                  }
          }
      };
      
      //待注册函数
      function MyClass(msg){
          this.msg=msg;
          this.show=function(){
          console.log(this.msg+' is called.');
        };
      }
      
      var obj1=new MyClass('listener1');
      var obj2=new MyClass('listener2');
      emitter.register(obj1.show.bind(obj1));
      emitter.register(obj1.show.bind(obj2));
      emitter.onOpen();
    
  • 使用匿名函数注册

加载

跳转

  • location.href改写 : 会记录到history
  • location.assign(url) : 同href改写
  • location.replace(url) : 不会记录到history

关闭页面前提示

window.onbeforeunload = function(e){
	return 'some extra tips';
};
//点击其他链接则取消关闭提示
var dlinks = document.querySelectorAll('a');
for (var i = 0; i < dlinks.length; i++) {
	dlinks[i].onclick = function() {
		window.onbeforeunload = null;
	}
};

刷新

  • location.reload(true) : 忽略缓存刷新
  • location.reload(false) : 不忽略缓存刷新
  • location.reload() : 同false

Dom

  • live对象,始终具有Dom树的实体引用
  • 若遍历大量dom结果集(nodelist),转换为数组会更快 :Array.slice(结果集)
  • DocumentFragment对重复添加createElement,减少重绘次数

location

属性

|属性 |描述|
|:— |:—:|
|hash |设置或返回从井号 (#) 开始的 URL(锚)|
|host |设置或返回主机名和当前 URL 的端口号|
|hostname| 设置或返回当前 URL 的主机名|
|href |设置或返回完整的 URL|
|pathname| 设置或返回当前 URL 的路径部分|
|port |设置或返回当前 URL 的端口号|
|protocol| 设置或返回当前 URL 的协议|
|search |设置或返回从问号 (?) 开始的 URL(查询部分)|

这些属性都是可读写,相当方便跳转哦

方法

方法 描述
assign() 加载新的文档
reload() 重新加载当前文档
replace() 用新的文档替换当前文档

####Tips

  • 当一个 Location 对象被转换成字符串,href 属性的值被返回。这意味着你可以使用表达式 location 来替代 location.href。
  • replace() 方法不会在 History 对象中生成一个新的记录。当使用该方法时,新的 URL 将覆盖 History 对象中的当前记录。
Questions? Leave a comment below or email: newbvirgil@gmail.com
Share   |  Updated: