首先編寫一段求長方形的面積周長程式:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rectangle</title>
</head>
<body>
<!--題目: 定義一個創建“長方形”的構造函數(有參數,通過參數給屬性賦值)
屬性:長(length);(實例屬性)
寬(width);(實例屬性)
方法:求面積;(原型方法)
求周長;(原型方法)
通過這個構造函數創建出3個不同的對象,並調用對象方法計算對象的面積和周長;
-->
<script>
//構造函數,傳遞一個對象obj
function Rectangle(obj) {
this._init(obj);
}
//原型替換
Rectangle.prototype = {
//使得原型函數又指向Rectangle函數對象
constructor:Rectangle,
//原型的方法,對初始化屬性進行單獨封裝成對象,用對象傳遞
_init: function (obj) {
//css6中的方法,就是把obj對象中的屬性全部傳到this裏
Object.assign(this, obj);
},
area: function () {
return this.width * this.length;
},
perimeter: function () {
return this.width * 2 + this.length * 2;
}
};
//new對象
var r1 = new Rectangle({length: 10, width: 10});
var r2 = new Rectangle({length: 20, width: 90});
var r3 = new Rectangle({length: 50, width: 60});
//output information
console.log("r1長方形面積爲: " + r1.area());
console.log("r1長方形周長爲: " + r1.perimeter());
console.log("r2長方形面積爲: " + r2.area());
console.log("r2長方形周長爲: " + r2.perimeter());
console.log("r3長方形面積爲: " + r3.area());
console.log("r3長方形周長爲: " + r3.perimeter());
</script>
</body>
</html>
我們看看程式的內存分配是怎樣的:
上課老師筆記:
--------------------------
----------------------
----------------------------------
------------------------------
--------------------------
-------------------------
-----
---
---
----
-----
---