zoukankan      html  css  js  c++  java
  • javascript中有关this的使用

    this在面向对象编程中非常重要,他的值取决于调用的模式。

    在Javascript中有4种调用模式:方法调用模式、函数调用模式、构造器调用和apply调用。

    1. 方法调用模式:当一个方法被调用时,this被绑定到该对象。方法可以使用this访问自己所属的对象,this到对象的绑定发生在调用的时候。如下:

    var myObject={

      value:0,

      increment:function (inc){

        this.value+=typeof inc ==='number' ?  inc:1;

      }

    };

    myObject.increment(1);

    document.writeln(myObject.value);   //1

    myObject.increment(2);

    document.writeln(myObject.value);   //3

    2.函数调用模式:当一个函数并非一个对象的属性时,他就是呗当做一个函数来调用的。

    myObject.double=function () {

      var that=this; 

      var heleper=function () {

        that.value=add(that.value,that.value);

      };

      helper();             //以函数形式调用helper

    };

    3.构造器调用:如果在一个函数前面带上new来调用,那么将会创建一个到该函数的prototype成员的新对象,同时this会被绑定到那个新对象上。

    //创建一个构造器函数。

    var Quo=fucntion (string){

      this.status=string;

    };

    Quo.prototype.get_statue=function () {

      return this.status;

    }

    var myQuo=new Quo("confused");

    document.writeln(myQuo.get_status()); //打印confused

    4.apply调用模式

  • 相关阅读:
    微信小程序登录(包括获取不到unionid的情况)
    ionic生成签名的APK方法总结
    iframe的简单使用方法
    常见的浏览器端的存储技术:cookie
    AJAX 过程总结
    react相关知识总结2
    正则表达式相关知识点
    vue相关知识汇总
    react相关知识汇总
    Vue-Router核心实现原理
  • 原文地址:https://www.cnblogs.com/xmll/p/4978275.html
Copyright © 2011-2022 走看看