this关键字笔记

来源:互联网 发布:政府转移支付数据 编辑:程序博客网 时间:2024/06/03 20:15

1.问题提出
需求:在实际编程中,我们可能有这样的需求,当我们创建一个对象后,就希望该对象自动的拥有某些属性(例如,我们创建了一个person对象,就希望该对象自动拥有name和age属性)?

function Person(){}var p1=new Person();window.alert(p1.name);//会输出什么?(输出undefined)

2.使用this来解决

function Person(){this.name="abc";this.age=90;}var p1=new Person();var p2=new Person();window.alert(p1.name+" "+p2.name); 

区别:

function Person(){var name="abc"; //如果这样去使用name这个属性是私有的var age=90;this.name2="abc2"; //这样使用表示name2这个属性是公开的this.show=function(){  //这个就是Person类的一个公开的方法window.alert(name+" "+age);show2();  //公有调私有}function show2(){ //这是Person类的一个私有方法,只能在Person类中使用window.alert("show2()"+name+" "+age);}}var p1=new Person();window.alert(p1.name+" "+p1.age); //错误window.alert(p1.name2);  //正确p1.show();  //公开方法调用p1.show2();  //公有调私有

3.进一步理解this
(1)哪个对象实例调用this所在的函数,那么this就代表哪个对象实例。
(2)this不能在类定义的外部使用,只能在类定义的方法中使用。

function test1(){alert(this.v);}var v=90;window.test1();  //等价于test1() 输出90
function Person(){this.abc=function(){window.alert(this.v);}}var p=new Person();p.v="hello";p.abc();  //因为p调用函数this.abc=function(),所以p就是this

图解:
这里写图片描述

原创粉丝点击