• JS Apply AOP EXTEND


    /*Apply 方法的妙用*/

    /*1.数组最大值*/
    console.log(Math.max(19, 2, 25, 16, 78));//78
    /*如果参数是一个一维数组*/
    var arr = [19, 2, 25, 16, 78];
    console.log(Math.max(arr));//NaN
    console.log(Math.max.apply(null, arr));//78

    /*多维数组可以这么修改:*/
    var a = [1, 2, 3,
    [5, 6],
    [1, 4, 8]
    ];
    /*转化为一维数组*/
    var ta = a.join(",").split(",");
    console.log(Math.max.apply(null, ta)); //8


    /*2.Push数组*/
    var arr1 = [1, 2, 3];
    var arr2 = [3, 4, 5];
    arr1.push(arr2);
    console.log(arr1); /*[1, 2, 3, [3, 4, 5] ] */

    var arr1 = [1, 2, 3];
    Array.prototype.push.apply(arr1, arr2);
    console.log(arr1); /*[1, 2, 3, 3, 4, 5 ] */


    /*3.继承*/
    var Class = {
    create : function(){
    return function(){
    this.initialize.apply(this,arguments);
    }
    }
    }

    var Animal = Class.create();
    Animal.prototype.initialize = function(species,name){
    this.species = species;
    this.name = name;
    }

    a = new Animal("Cat","Buddy");


    var GoldenRetriever = Class.create();
    GoldenRetriever.prototype.initialize = function(species,name,age){
    Animal.prototype.initialize.apply(this,arguments);
    this.age = age;
    }

    g = new GoldenRetriever("Dog","Puppy","2");
    console.log(a);//Object name: "Buddy", species: "Cat"
    console.log(g);//Object age: "2", name: "Puppy", species: "Dog"


    /*4.aop*/
    Function.prototype.before = function(func){
    var _this = this;
    return function(){
    if (func.apply(this,arguments) === false){
    return false;
    }
    return _this.apply(this,arguments);
    }
    }

    window.onload = function(){
    console.log("onload.");
    }

    window.onload = (window.onload || function(){} ).before(function(){
    console.log("onload before.")
    }) //onload before. onload.

     

    Function.prototype.after = function(func){
    var _this = this;
    return function(){
    var result = _this.apply(this, arguments);
    if (result === false) return false;
    func.apply(this,arguments);
    return result;
    }
    }

    window.onload = (window.onload || function(){}).after(function(){
    console.log("onload after.")
    }) //onload before. onload. onload after.

  • 相关阅读:
    php header 跳转 ie问题
    Filter过滤不了Action的问题
    DB2中sql语句占位符问题
    LL(1)文法
    算法分析实验报告词法分析器
    大数据概述
    2016.9.30 编译原理词法分析器
    131有确定性的有穷自动机
    Python基础综合练习
    组合数据类型练习
  • 原文地址:https://www.cnblogs.com/mguo/p/3123738.html
Copyright © 2020-2023  润新知