zoukankan      html  css  js  c++  java
  • this对象

    1、改变this

    A:call()方法:

    function sayNameForAll(label){
        console.info(label + ":" + this.name);
    }
    
    var person1 = {
        name : "Nicholas"
    };
    
    var person2 = {
        name = "Greg"
    };
    
    var name = "Michale";
    
    sayNameForAll.call(this,"global");       //outputs “global:Michale”
    sayNameForAll.call(person1,"person1");   //outputs "person1:Nicholas"
    sayNameForAll.call(person2,"person2");   //outputs    "person2:Greg"

    B:apply()方法:和call()方法一样,接受两个参数,this的值和一个数组或者类似数组的对象,内含需要被传入函数的参数,不需要像使用call()那样一个个指定参数

    function sayNameForAll(label){
        console.info(label + ":" + this.name);
    }
    
    var person1 = {
        name : "Nicholas"
    };
    
    var person2 = {
        name = "Greg"
    };
    
    var name = "Michale";
    
    sayNameForAll.apply(this,["global"]);       //outputs “global:Michale”
    sayNameForAll.apply(person1,["person1"]);   //outputs "person1:Nicholas"
    sayNameForAll.apply(person2,["person2"]);   //outputs    "person2:Greg"
  • 相关阅读:
    [SDOI2016]排列计数
    Broken robot
    环路运输
    naptime
    Accumulation Degree
    选课
    没有上司的舞会
    金字塔
    Polygon
    石子合并
  • 原文地址:https://www.cnblogs.com/zhanghuiyun/p/5658323.html
Copyright © 2011-2022 走看看