1. 程式人生 > >js原型鏈部分詳細使用說明案例

js原型鏈部分詳細使用說明案例

一個 foo *** 根據 str fin 屬性 font itl

1. ‘index.html‘文件

```html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>js原型講解</title>

</head>

<body>

<script src=‘js/person.js‘></script>

<script src=‘js/student.js‘></script>

<script src=‘js/coder.js‘></script>

<script>

var person = new Person(‘Jack‘,18,‘男‘);

person.sleep();

person.dating();

person.eat(‘蛋炒飯‘);

person.birthday();

/////student實例化對象

/***

* 實例化後的對象在查找屬性或者方法的時候

* 首先在 this 自己內部查找

* 如果沒有找到 就會到原型中查找

* 如果原型中沒有,那麽就會去原型的原型繼續查找

* ...

* 直到找到為止 如果沒有找到那麽返回undefined或者報錯

*/

var student = new Student(‘小明‘,15,‘男‘,‘縣一中‘);

console.dir(student);

student.sleep();

student.dating();

student.eat(‘蛋炒飯‘);

student.birthday();

student.goSchool();

var coder = new Coder(‘Jerry‘,25,‘男‘,‘MS‘);

coder.sleep();

coder.work();

console.log(coder);

</script>

</body>

</html>

```

2. ‘js/person.js‘文件

```javascript

/****

* 定義一個Person對象

* 包含 name age gender 三個屬性

*/

function Person(name, age,gender) {

this.name = name;

this.age = age;

this.gender = gender;

}

////Person的原型

Person.prototype = {

/////睡覺

sleep:function(){

console.log(this.name + ‘每天睡覺八小時‘);

},

////吃飯 傳入參數food

eat:function(food){

console.log(this.name+‘特別愛吃‘+food);

},

////不需要參數

dating:function(){

console.log(‘單身狗‘);

},

////出生年份,根據年齡計算 不需要參數

birthday:function(){

var birthYear = (new Date()).getFullYear()-this.age;

console.log(this.name+‘的出生在‘+birthYear+‘年‘);

}

}

```

3. ‘js/student.js‘文件

```javascript

function Student(name,age,gender,school){

this.school = school;

Person.apply(this,[name,age,gender]);

}

// function EmptyFun(){}

// ///設置空對象的原型為Person的原型

// EmptyFun.prototype = Person.prototype;

// var temEmptyFun = new EmptyFun(); ////實例化的一個空對象

// Student.prototype = temEmptyFun; ///設置學生的原型為實例化的空對象

// Student.prototype.constructor = Person

//Object.create()可以通過你提供的原型創建一個新對象,

//這個新對象的原型就是create()的第一個參數

Student.prototype = Object.create(Person.prototype);

Student.prototype.constructor = Student

////為學生原型定義一個方法 goSchool

Student.prototype.goSchool = function(){

console.log(this.name + ‘每天早上八點準時去‘+this.school);

}



/////為學生創建一個dating方法

Student.prototype.dating = function(){

console.log(‘學校禁止早戀!‘);

}

```

4. ‘js/coder.js‘文件

```javascript

function Coder(name,age,gender,company){

Student.apply(this,[name,age,gender,company]);

}

Coder.prototype = Object.create(Student.prototype);

Coder.prototype.work = function(){

console.log(‘writing code ....../n fix bugs‘);

}

```

js原型鏈部分詳細使用說明案例