• js中的call及apply的运用


    格式:

    obj.call(thisObj, arg1, arg2, ...);  参数为字符 obj.apply(thisObj, [arg1, arg2, ...]); 参数为数组

    例一:sub函数赋值给this 

    其实就是动态的改变this了,下面例子就说明了。。。
    function add(a, b){
        console.dir(this);
    }
    function sub(a, b){
        console.dir(this);
    } 
    add(1,2);                         "Window" 
    sub(1,2);                         "Window" 
    add.call(sub, 1, 2);          "sub(a, b)" 
    sub.apply(add, [1, 2]);    "add(a, b)"
    --------------------------------------------
    function add(j, k){
        alert(j+k);
        this(j,k);
    }
    
    function sub(j, k){
        alert(j-k);
    }
    add.call(sub, 5, 3); //把sub函数赋值给this 输出8  2
    add.apply(sub, [5, 3]); //8  2        

    例二: 点击把#content赋值给函数中的this来改变颜色和样式

    function color() {
        this.style.color = 'red';
    }
    function size() {
        this.style.fontSize = '54px';
    }
    window.onload = function() {
        document.getElementById('content').onclick = function() {
            color.call(this);
            size.apply(this);
        }
    }

    hello  点击后变成  hello

    例三:通过call和apply,我们可以实现child对象继承parent。

    var Parent = function(){
        this.name = "yjc";
        this.age = 22;
    }
    var child = {};
    console.log(child);//Object {} ,空对象
    Parent.call(child);
    console.log(child); //Object {name: "yjc", age: 22}
  • 相关阅读:
    我知道点redis-数据结构与对象
    白帽子-第十四章 PHP安全
    白帽子-第二篇 客户端脚本安全
    网络编程
    inline的作用
    Windows静态库和动态库区别
    简单实现图片上传预览
    Java 通用正则表达式
    C#+Mysql 图片数据存储
    FileUpload转换为字节
  • 原文地址:https://www.cnblogs.com/xujian2016/p/6084990.html
Copyright © 2020-2023  润新知