2016-12-02 6 views
0

デカルト座標ライブラリで作業しています。クラスを簡単に作成し、プロトタイプを定義してインスタンスを作成しようとします。新しいプロトタイプ定義なしで作成されたオブジェクト

しかし、この単純なケースでは、私のデカルトオブジェクトにはメソッドがありません。

let Cartesian = function(instance, opts) { 
    let pos = opts.pos || {x:0, y: 0} 
    /* .. Logic here .. */ 
    return {pos: pos} 
} 

console.log("Before : ", Cartesian.prototype.getPosition) 

Cartesian.prototype.getPosition = function() { 
    return true 
} 

console.log("After : ", Cartesian.prototype.getPosition) 

CartesianExport = { 
    create: function (instance, opts) { 
    console.log("Create new : ", Cartesian.prototype.getPosition) 
    let c = new Cartesian(instance, opts) 
    console.log("Created : ", c, c.getPosition) 
    return c 
    } 
} 

module.exports = CartesianExport 

そして、これは私のコンソール

Before : undefined 
After : function() { return true } 
Create new : function() { return true } 
Created : Object {pos: Object} undefined 

である私はそれを使用しようとすると、私はcartesian.getPosition is not a functionを得た理由を私は理解していません。

+1

'Cartesian'では 'return {pos:pos}' - なぜそれをやっていますか?私はあなたがJavascriptのコンストラクタがどのように動作するのか誤解していると思います。 – user2357112

+0

私の場合、私は他の属性を返します。その場合、 'c.pos' – Arthur

+1

からアクセスできます。返されるオブジェクトは'デカルト 'ではありません –

答えて

0

この使用:

function Cartestian(opts) { 
    this.pos = opts.pos || {x: 0, y: 0}; 
} 

を、あなたのコンストラクタでreturn {pos: pos};を言うとき、プロトタイプレスオブジェクト{pos: pos}はなくCartesianの新しいインスタンスを返します。インスタンスは戻り値でオーバーライドされます。したがって、new Cartesian(...)は、プロトタイプのないオブジェクトに評価されます。これは私が意味するものです:

function IncorrectlyDefined(obj) { 
    return obj; 
} 

var someObj = {x: 0, y: 0}; 
var x = new IncorrrectlyDefined(someObj); 
// x === someObj 
+0

解決策をより明確にする。 'new Object'でClassプロトタイプを取得するには、' constructor'で 'this'を返す必要があります – Arthur

-3

あなたの取得していないgetesosation関数の宣言はありません。だからUは関数を宣言することができます。c.getPosition関数あなたはthat.dataを得ることができます

+0

http://www.w3schools.com/js/js_object_prototypes.asp – Arthur

関連する問題