热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

javascript中有关this的使用

this在面向对象编程中非常重要,他的值取决于调用的模式。在Javascript中有4种调用模式:方法调用模式、函数调用模式、构造器调用和apply调用。1.方法调用模式:当一个方法被调用时,thi

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


推荐阅读
author-avatar
buxin81588_416
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有