this关键字与构造函数

来源:互联网 发布:mysql创建数据库命令 编辑:程序博客网 时间:2024/04/29 04:23

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。




原创粉丝点击