JavaScript的對象和繼承

來源:互聯網
上載者:User

JavaScript的對象和繼承

本文記錄一種JavaScript的對象定義和繼承的書寫方式,也是目前使用比較普遍的一種。1、定義對象(混合的建構函式和原型方式)// 屬性在建構函式裡定義function Person(name, age, sex) {this.name = name;this.age = age;this.sex = sex;}// 方法在原型裡定義Person.prototype.hello = function() {alert("Hello, my name is " + this.name);}Person.prototype.say = function(str) {alert("This is " + str);}// 執行個體var p = new Person("Jim", 23, "M");p.hello();p.say("Car");2、繼承的實現// 定義子類屬性function Student(name, age, sex, score) {Person.call(this, name, age, sex);  // (1) 可看作建構函式,對繼承的父類屬性並初始化this.score = score;}// 定義子類方法Student.prototype = new Person();  // (2) 通過對子類的prototype進行一個父類無參建構函式的賦值,來繼承父類的屬性和方法,但繼承的屬性值都為空白,需通過(1)進行初始化Student.prototype.sayScore = function() {alert("My score is " + this.score);}注: a、子類在進行繼承父類時,上面的(1)和(2)兩步都是必須的。b、若子類定義了一個跟父類同名的方法,則無論子類的同名方法參數是否與父類一樣,都會覆蓋父類的同名方法,子類對象調用時調的是子類的方法。c、通過prototype定義方法時,需通過" Object.prototype.methodName = function() {...} "的方式,否則子類無法直接通過方法名調用父類方法。// 執行個體var s = new Student("Andy", 22, "F", 100);s.hello();s.say("Book");s.sayScore();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.