2015-03-02 128 views
0

此代码示例推导,如果你看到的代码中,B.prototype的doSomething()方法是调用A.protoype的doSomething()同时将B的this OBJ从Mozilla原型继承返回值

扭捏。那么为什么这个代码的输出从B.prototype而不是A.prototype返回呢?可能是我在这里失去了一些东西,但无法弄清楚为什么。

function A(a) { 
    this.varA = a; 
} 

// What is the purpose of including varA in the prototype when A.prototype.varA will always be shadowed by 
// this.varA, given the definition of function A above? 
A.prototype = { 
    varA: null, // Shouldn't we strike varA from the prototype as doing nothing? 
    // perhaps intended as an optimization to allocate space in hidden classes? 
    // https://developers.google.com/speed/articles/optimizing-javascript#Initializing instance variables 
    // would be valid if varA wasn't being initialized uniquely for each instance 
    doSomething: function(a) { 
     return "DoSomething From A" 
    } 
} 

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); 
      return "DoSomething From B" // call super 
       // ... 
     }, 
     enumerable: true, 
     configurable: true, 
     writable: true 
    } 
}); 
B.prototype.constructor = B; 

var b = new B(); 
b.doSomething(7) 

回答

1

调用A.prototype.doSomething,你就是不能做与上A原型方法返回的任何有价值的东西。

  1. A.prototype.doSomething.apply(this, arguments);返回 “从A DoSomething的” 并且该值被丢弃
  2. return "DoSomething from B"作为返回的b.doSomething(7)返回值。

更改return s到console.log S和你会看到它的工作原理就像你期望的那样,你会得到A消息,则B消息。

+0

谢谢,就是这样。傻我。 – Minty 2015-03-02 18:51:27