Javascript 基礎之原型鏈

構造函數(shù)、構造函數(shù)實例、構造函數(shù)原型

function Student (name) {
    this.name = name;
}
Student.prototype.getName = function() {
    console.log(this.name);
};
var student = new Student("Spursyy");
student.getName();

function Student (name) { } - 這是構造函數(shù)
var student = new Student("Spursyy") - 這是構造函數(shù)實例

Page 1

Page 1, highlight 部分即為構造函數(shù)原型

Page 2

根據(jù)Page 1 與 Page 2, 可以歸納出構造函數(shù),構造函數(shù)原型與構造函數(shù)實例之間的關系圖譜如下,

Page 3

原型鏈

function Student (age) {
    this.age = age;
}
Student.prototype.getAge = function() {
    console.log(this.age);
};

function People(name) {
    this.name = name;
}
People.prototype = new Student("18");
People.prototype.getName = function() {
    console.log(this.name);
};
var people = new People("Spursyy"); 
people.getName();       //  Spursyy
people.getAge();          //  18

觀察上面代碼,把Student構造函數(shù)實例化對象賦值給People構造函數(shù)原型,
這樣Student 的構造函數(shù)原型上的getAge(), 就傳遞給People構造函數(shù)原型。

Page 4

原形鏈問題

var person = {
    name: "Spursy",
    age: 15
}
var student = Object.create(person);
student.name = "YY";

console.log(`person name: ${person.name}`);   // YY
console.log(`student name: ${student.name}`);   // Spursy
var animal = {
    catagory: {
        dogA: "small dogs"
    }
}
var dog = Object.create(animal);
dog.catagory = {
    dogB: "big dogs"
}
console.log(`animal catagory: ${JSON.stringify(dog.catagory)}`);     // {dogA: "small dogs"}
console.log(`animal catagory: ${JSON.stringify(animal.catagory)}`);      // {dogB: "big dogs"}
為什么后面的代碼修改的是原型鏈上的屬性呢?

這個問題主要的原因是由于基本類型與引用類型的區(qū)別,構造函數(shù)的animal 的屬性catagory 是個對象(引用數(shù)據(jù)類型),系統(tǒng)會為這個對象單獨開辟一個空間,dog 作為animal 構造函數(shù)的子對象,自然會共享catagory 這個引用數(shù)據(jù)類型。故在子對象上修改catagory就是在修改內存中的catogory, 因此父的catagory 對象也是會被修改。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容