2015-03-02 125 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