前言
本章主要介紹的是JS中構(gòu)造函數(shù)是怎么使用的.
- 思路 : 首先定義一個(gè)對(duì)象函數(shù),將函數(shù)的所有屬性都定義為空,然后創(chuàng)建構(gòu)造函數(shù),直接使用點(diǎn)語(yǔ)法,給對(duì)象函數(shù)賦值,然后打印.
- 1, 簡(jiǎn)單創(chuàng)建一個(gè)構(gòu)造函數(shù)
//// 創(chuàng)建一個(gè)student函數(shù)
function student(){
console.log('我真的是夠了,忘記吃中午飯了');
}
// 函數(shù)的調(diào)用
student();
// 構(gòu)造函數(shù),批量生產(chǎn)函數(shù)
var student1 = new student();
// 使用new可以快速創(chuàng)建函數(shù),相當(dāng)于OC中的[[student alloc] init]
console.log(typeof student1); // object
- 根據(jù)例子可以得出一個(gè)結(jié)論,創(chuàng)建一個(gè)構(gòu)造函數(shù),主要是通過(guò)new來(lái)創(chuàng)建的.
- 2, 批量生產(chǎn)構(gòu)造函數(shù)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>如何批產(chǎn)對(duì)象</title>
</head>
<body>
<script type="text/javascript">
// 構(gòu)造函數(shù), 沒(méi)有參數(shù)的時(shí)候
var Dog = function(){
this.name = null;
this.age = null;
this.height = null;
this.run = function(){
console.log(this.name + '一直在雨中奔跑,風(fēng)一樣的狗');
};
this.eat = function(meat){
console.log(this.name + '尼莫,只知道吃肉');
}
}
// 批量生產(chǎn)對(duì)象
var dog1 = new Dog();
dog1.name = '大黃';
dog1.age = 1;
dog1.height = 1.80;
dog1.width = 150;
dog1.eat('吃屎吧你');
dog1.run();
var dog2 = new Dog();
dog2.name = '大阿輝';
dog2.age = 2;
dog2.width = 70;
dog2.eat('五花肉');
dog2.run();
console.log(dog1, dog2);
</script>
</body>
</html>
-
運(yùn)行結(jié)果 :
- 3, 有參數(shù)批量生產(chǎn)對(duì)象
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>如何批產(chǎn)對(duì)象</title>
</head>
<body>
<script type="text/javascript">
<!--有參數(shù)的時(shí)候-->
var dog = function(name, age, width){
this.name = name;
this.age = age;
this.width = width;
this.run = function(){
console.log(this.name + '雨中奔跑');
};
this.eat = function(meat){
console.log(this.name + meat);
}
}
// 批量生產(chǎn)構(gòu)造函數(shù)
var dog1 = new dog('大黃', 1, 150);
var dog2 = new dog('大灰', 2, 100);
dog1.run();
dog2.eat('只會(huì)吃屎');
console.log(dog1.name,dog1.width,dog1.age);
console.log(dog2.name,dog2.width,dog2.age);
</script>
</body>
</html>
- 運(yùn)行結(jié)果
- 總結(jié) : 本章重點(diǎn) :new的使用,快速創(chuàng)建一個(gè)構(gòu)造函數(shù)對(duì)象