this关键字与构造函数

1.在函数内用到对象的属性时,常要用到this关键字,指出是这个对象的属性

如:

var movie1 = 

{

title:"play 9",

genre:"cult classic",

rating:5,

showtimes:["3:00pm", "7:00pm", "9:00pm"],

getNextShowing:function() {

for (var i = 0; i<this.showtimes.length; i++)

{

var showtime = getTimeFromString(this.showtimes[i]);

return "Next showing of" this.title + "is" + this.showtimes[i];

}

}


}


2.构造函数是一种特殊的函数,就像一个小工厂,可以加工成带有相同属性/方法,不同值的对象。充分利用代码重用。

创建:首字母大写,this属性和形参名称保持一致

function Dog (name,breed, weight)

{

this.name = name;

this.breed = breed;

this.weight = weight;

this.bark = function() {

if(this.weight > 25) {

alert (this.name + "says woof!");

}

else {

alert (this.name + "says Yip");

}

}

}

使用:使用new关键字创建对象,使用方法时注意加()

var fido = new Dog ("fido", "Mixed", 38);     //fido对象的3个属性

var tiny = new Dog ("tiny", "Chawalla", 8);

fido.bark();   //调用bark方法

tiny.bark();


3.见上例,只要在一个方法代码中放入this,就会把它解释为调用这个方法的对象的一个引用。所以fido.bark(); this指向fido对象,tiny.bark(); this指向tiny对象。而不是Dog。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值