1. 程式人生 > 其它 >js 繼承和原型鏈

js 繼承和原型鏈

1.物件

<script>
        function Car(name,speed){
            this.name=name;
            this.speed=speed;
        }
        Car.prototype.showName=function(){ //獨立出來的公共空間,減少記憶體
            console.log(this.name);
        }
        var car=new Car("奧迪",300); //new建立新空間,每次new都會複製name,speed
        var
car2=new Car("賓士",280); console.dir(car); //輸出結構 console.dir(car2); car.showName(); //呼叫showName()方法 </script>

2.繼承

<script>
        //把Student()和People()建立關係--》讓Student()間接呼叫People()裡的showName
        function People(name){
            this.name=name;
        }
        People.prototype.showName
=function(){ console.log(this.name); } function Student(){ } Student.prototype=new People("德爾");//把Student.prototype給People() Student.prototype.study=function(){ console.log("學習"); } var stu=new Student(); // stu.study();
// stu.showName(); //原型鏈 實現繼承 原型鏈的最終指向是object,object的原型是null //console.dir(stu.__proto__===Student.prototype); //console.dir(Student.prototype.__proto__===People.prototype); // console.dir(stu.__proto__.__proto__===People.prototype); // console.dir(People.prototype.__proto__.__proto__); console.dir(stu.__proto__.__proto__.__proto__.__proto__); //物件的原型 __proto__ //建構函式的原型 prototype </script>