2017-05-06 19 views
2

今日はFunction.prototype.bind()のMDNドキュメントを読んでいました。セクションBound functions used as constructorsの下に、私がかなり理解できない例があります。バインドと継承の相関の理解について

私はaxisPointがのインスタンスである理由私ははっきりと見ることができるのNode.js(v.4.4.5)とGoogle Chromeの(v58.0.3029.81)の両方で

function Point(x, y) { 
    this.x = x; 
    this.y = y; 
} 

Point.prototype.toString = function() { 
    return this.x + ',' + this.y; 
}; 

var p = new Point(1, 2); 
p.toString(); // '1,2' 

var emptyObj = {}; 
var YAxisPoint = Point.bind(emptyObj, 1/*x*/); 

var axisPoint = new YAxisPoint(5); 
console.log(axisPoint.toString()); // '1,5' 

console.log(axisPoint instanceof Point); // true 
console.log(axisPoint instanceof YAxisPoint); // true 
console.log(new Point(17, 42) instanceof YAxisPoint); // true 

を以下のコードを実行しましたPointYAxisPointの両方です。しかし、どのように世界でnew Point(17,42)YAxisPointのインスタンスになることができますか?

答えて

4

しかし、どのように世界でnew Point(17,42)YAxisPointのインスタンスになることができますか?

ため、バインドされた機能(.bind()呼び出しから作成されたもの)と特別なinstanceof作品。通常、オブジェクトがコンストラクタ.prototypeから継承するかどうかをチェックしますが、バインドされた関数には.prototypeがありません。代わりに、バインドされた関数にinstanceofを使用すると、そのオブジェクトがターゲット関数のインスタンスであるかどうかがチェックされます(bind()が呼び出されました)。だから、

… instanceof YAxisPoint 

… instanceof Point 

とまったく同じであるあなたは、スペック(ES5ES6)でこれを確認することができます。