js继承

来源:互联网 发布:python split删除空格 编辑:程序博客网 时间:2024/06/03 17:15
var o = {  a: 2,  m: function(){    return this.a + 1;  }};console.log(o.m()); // 3// 当调用 o.m 时,'this'指向了o.var p = Object.create(o);// p是一个对象, p.[[Prototype]]是o.p.a = 12; // 创建 p 的自身属性a.console.log(p.m()); // 13// 调用 p.m 时, 'this'指向 p. // 又因为 p 继承 o 的 m 函数// 此时的'this.a' 即 p.a,即 p 的自身属性 'a'
function A(a){  this.varA = a;}// 以上函数 A 的定义中,既然 A.prototype.varA 总是会被 this.varA 遮蔽,// 那么将 varA 加入到原型(prototype)中的目的是什么?A.prototype = {  varA : null,  // 既然它没有任何作用,干嘛不将 varA 从原型(prototype)去掉?      // 也许作为一种在隐藏类中优化分配空间的考虑?      // https://developers.google.com/speed/articles/optimizing-javascript#Initializing instance variables      // 将会验证如果 varA 在每个实例不被特别初始化会是什么情况。  doSomething : function(){    // ...  }}function B(a, b){  A.call(this, a);  this.varB = b;}B.prototype = Object.create(A.prototype, {  varB : {    value: null,     enumerable: true,     configurable: true,     writable: true   },  doSomething : {     value: function(){ // override      A.prototype.doSomething.apply(this, arguments); // call super      // ...    },    enumerable: true,    configurable: true,     writable: true  }});B.prototype.constructor = B;var b = new B();b.doSomething();

最重要的部分是:

  • 类型被定义在 .prototype 中
  • 而你用 Object.create() 来继承
1 0
原创粉丝点击