[JavaScript]关于prototype继承

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");
  };
}


热门相关:地球第一剑   寂静王冠   霸皇纪   大神你人设崩了   寂静王冠