When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object call ...
When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain. It is possible to mutate any member of the prototype chain or even swap out the prototype at runtime, so concepts like static dispatching do not exist in JavaScript.
每個實例對象(object)都有一個私有屬性(稱之為 __proto__)指向它的構造函數的原型對象(prototype)。該原型對象也有一個自己的原型對象(__proto__),層層向上直到一個對象的原型對象為 null。根據定義,null 沒有原型,並作為這個原型鏈中的最後一個環節。
幾乎所有 JavaScript 中的對象都是位於原型鏈頂端的 Object 的實例。
就是說,JavaScript 中的對象都是繼承而來,所有的對象都是由一個最簡單的對象不斷增加特定的功能而形成的。
使用prototype添加屬性和方法
Before:
//創建類
function Duck(){
name = "RoastDuck";
age = 18;
hobby = "eat";
}
//添加屬性
Duck.prototype.home("China");
//添加方法
Duck.prototype.action=function(){
console.log("Roast is enoding");
};
After:
function Duck(){
name = "RoastDuck";
age = 18;
hobby = "eat";
//添加的屬性
home = "China";
//添加的方法
action = function(){
console.log("Roast is enoding");
};
}