• 类的进阶


    apply的两个参数分别是上下文和参数组成的数组。

    function.apply(this, [1, 2, 3]);

    call的两个参数是多个,也就是不用数组包裹参数。

    function.call(this, 1, 2, 3);

    常常会遇到事件内部没有this的情况,怎么处理呢?

    低级方法:

    $('.clicky').click(function(){
      $(this).hide();
    });
    
    $('p').each(function(){
      $(this).remove();
    });
    var clicky = { 
      wasClicked: function(){
    /* ... */ }, addListeners: function(){   var self = this;
      $('.clicky').click(function(){   self.wasClicked() }); } }; clicky.addListeners();

    高阶方法:

    var proxy = function(func, thisObject){ 
      return(function(){
      return func.apply(thisObject, arguments); });
    };
    
    var clicky = { wasClicked: function(){
    /* ... */ },
    addListeners: function(){ 
      var self = this;
      $('.clicky').click(proxy(this.wasClicked, this)); } };

    jQuery中proxy()用来实现将上下文传给事件的回调函数的功能

    $('.clicky').click($.proxy(function(){ /* ... */ }, this));

    apply还可以用来作委托:

    var App { log: function(){
    if (typeof console == "undefined") return;
    //arguments是当前调用的作用域内解释器内置的用来保存参数的“数组”。
    //因为他是不可变的,需要jquery.makArray()把它转换成真的数组。
    var args = jQuery.makeArray(arguments);
    // 插入一个新的参数 
    args.unshift("(App)");
    // 委托给console 
    console.log.apply(console, args);
    } };

    待续。。

  • 相关阅读:
    django高级应用
    python第六章模块
    python第五章函数
    python第四章文件操作
    python第三章数据类型
    python第二章python入门
    python第一章计算机基础
    Python全栈day 05
    Python全栈day 04
    mysql 消息表分区方案
  • 原文地址:https://www.cnblogs.com/haimingpro/p/3823038.html
Copyright © 2020-2023  润新知