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调用模式

  • 相关阅读:
    存储过程分页
    连接数据库
    绑定数据
    有关最近做的项目中用到的日期控件
    循环累加 由for _foreach
    打印gridview 中的所有内容
    list<>操作
    创建表两个主键外键~~~
    连接数据库sql server 2005
    WPF控件编程
  • 原文地址:https://www.cnblogs.com/xmll/p/4978275.html
Copyright © 2011-2022 走看看