zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    个人作业-Alpha项目测试
    第三次作业-结对编程
    第二次作业
    第一次阅读作业
    canal同步mysql数据至es5.5.0
    工作一周年小结
    Java集合操作 遍历list并转map
    网易秋招校招编程题
    堆外内存总结
    网易秋招内推编程题题解
  • 原文地址:https://www.cnblogs.com/mguo/p/3123738.html
Copyright © 2011-2022 走看看