Javascript中對象繼承的實現小例

來源:互聯網
上載者:User

複製代碼 代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
/**
* json對象的格式
{key:value,key:value,key:value..}
*/
//建立對象的小例子
//-----1
var r={};
r.name="tom";
r.age=18;
//-----2
var r={name:"tom",age:20};//json對象
alert(r.age);
//---1,2是等價的
//-------原型模式的寫法
//----1
function Person(){};
Person.prototype.name="中國人";
Person.prototype.age=20;
//原型模式的簡寫形式--2
function Person(){};
Person.prototype={name:"中國人",
age:20,}
//-----1,2等價的
//================================
/* {name:"中國人",
age:20,}
上面的這種格式本身就是個對象,將其付給另一個對象的prototype,就使得
另一個對象的所有屬性。實質上就是繼承
*/
//================================
//標準的對象繼承例子,Person,Student
//定義一個Person對象
function Person(){};
Person.prototype.name="中國人";
Person.prototype.age=20;
var person=new Person();
//定義一個Student對象
function Student(){};
Student.prototype=person;
Student.prototype.girlFriend="可以有的";
var stu=new Student();
stu.laop="不許談戀愛";
alert(stu.name);//繼承自父物件的執行個體
alert(stu.laop);//自己新添加的屬性

//定義一個Teamleader對象的
function Teamleader(){};
Teamleader.prototype=new Student();//繼承自Student
Teamleader.prototype.teamNum=8;//Teamleader自己的屬性
//建立自己的執行個體
var teamleader=new Teamleader();
alert(teamleader.teamNum);
teamleader.girlFriend="也不可以有哦";
alert(teamleader.name);
//=================================
/*js中繼承的核心就是prototype*/
//=================================
</script>
</head>
<body>

</body>
</html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.