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");
};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/543121.html
標籤:JavaScript
上一篇:聊一聊js中元素定位的方法
