zoukankan      html  css  js  c++  java
  • bind方法

    // function f1(x,y) {
    // console.log((x+y)+"======"+this);
    // }
    // //复制了一份的时候,把参数传入到f1函数中,x====>10,y====>20,null就是this,默认是window
    // //bind方法是复制的意思,参数可以在复制的时候传进去,也可以在复制之后调用的时候传入进去
    // //apply和call是调用的时候改变this指向
    // //bind方法,是复制一份的时候,改变了this的指向
    // var ff=f1.bind(null);
    // ff(10,20);



    function Person(age) {
    this.age=age;
    }
    Person.prototype.play=function () {
    console.log(this+"====="+this.age);
    };
    function Student(age) {
    this.age=age;
    }
    var per=new Person(10);
    var stu=new Student(20);
    //复制了一份
    var ff=per.play.bind(stu);
    ff();
    /*
    * bind使用语法
    * 函数名字.bind(对象,参数1,参数2,......);====>返回值是复制之后的这个函数
    * 方法名字.bind(对象,参数1,参数2,......);====>返回值是复制之后的这个方法



    function ShowRandom() {
    this.number=parseInt(Math.random()*10+1);
    }
    //添加原型方法
    ShowRandom.prototype.show1=function () {
    //改变了定时器中的this 的指向,本来应该是window,现在是实例对象了
    window.setInterval(this.show2.bind(this),1000);
    };
    //添加原型方法
    ShowRandom.prototype.show2=function () {
    //显示随机数
    console.log(this.number);
    };
    //实例对象
    var sr=new ShowRandom();
    //调用方法,输出随机数
    //调用这个方法一次,可以不停的产生随机数字
    sr.show2();
  • 相关阅读:
    关于sqrt函数的使用
    电子商务
    随笔
    哈哈
    整体管理
    软件产品质量特性
    问题
    风险
    antd
    Flex布局大作用
  • 原文地址:https://www.cnblogs.com/lujieting/p/10082427.html
Copyright © 2011-2022 走看看