2016-10-15 10 views
1
function Point() { 
    this.xPos = 0; 
    this.yPos = 0; 
} 

Object.__defineGetter__.call(Point.prototype, "getPoint", function(){ 
    return "X: " + this.xPos + " Y: " + this.yPos; 
}); 

Object.__defineSetter__.call(Point.prototype, "setPoint", function(point){ 
    var parts = point.toString().split(', '); 
    parts[0] = this.xPos; 
    parts[1] = this.yPos; 
}); 

var newPoint = new Point(); 

newPoint.setPoint("44.5, 60.6"); 

console.log(newPoint.getPoint); 

それは私にエラーを返します:newPoint.setPointは関数ではありません。なぜあなたは私を助けることができますか?セッターとゲッターを処理しようとしています。セッターとゲッターのエラー

+1

なぜあなたはちょうど 'Point.prototype.getPoint = function(){...'を実行していません – adeneo

+0

これらの関数は、とにかく時代遅れです:http://stackoverflow.com/questions/6825191/what-are- definegetter-and-setsetter-functionsを定義します。 'get'または' set'を使います。 – Terry

+0

同じですか?申し訳ありません、私はJavaScriptの初心者です。アドバイスありがとう :) –

答えて

4

主な問題は、割り当て演算子=を使用してセッターが呼び出されることです。

newPoint.setPoint = "44.5, 60.6"; 

function Point() { 
 
    this.xPos = 0; 
 
    this.yPos = 0; 
 
} 
 

 
Object.__defineGetter__.call(Point.prototype, "getPoint", function(){ 
 
    return "X: " + this.xPos + " Y: " + this.yPos; 
 
}); 
 

 
Object.__defineSetter__.call(Point.prototype, "setPoint", function(point){ 
 
    var parts = point.toString().split(', '); 
 
    // the assignment to this.xPos and this.yPos was the wrong way around 
 
    this.xPos = parts[0]; 
 
    this.yPos = parts[1]; 
 
}); 
 

 
var newPoint = new Point(); 
 

 
// a setter is called by assigning a value to it 
 
newPoint.setPoint = "44.5, 60.6"; 
 

 
console.log(newPoint.getPoint);

また、コードを見て、誰のために従うことが容易になりますObject.definePropertyまたはObject.definePropertiesの標準APIを使用することができます。

Object.defineProperty(Point.prototype, "getPoint", { 
    get: function(){ 
    return "X: " + this.xPos + " Y: " + this.yPos; 
    }, 
    set: function() { 
    // stuff 
    } 
}); 

またはES6

class Point { 
    constructor() { 
    this.xPos = 0 
    this.yPos = 0 
    } 
    get getPoint() { 
     // stuff 
    } 
    set setPoint() { 
    // stuff 
    } 
} 
0

と私はdefineGetterdefineSetterを読んだから、もうあまり使用されません。

function Point() { 
    this.xPos = 0; 
    this.yPos = 0; 
} 

Object.defineProperties(Point, { 
    xPos: { 
    set: function(newValue) { 
     this.xPos = newValue; 
    }, 

    get: function() { 
     return this.xPos; 
    } 
    }, 

    yPos: { 
    set: function(newValue) { 
     this.yPos = newValue; 
    }, 

    get: function() { 
     return this.yPos; 
    } 
    } 
}); 

newPoint = new Point(); 
console.log(newPoint.xPos); 
newPoint.xPos = 45; 
console.log(newPoint.xPos); 

あなたはObject.definePropertieshereを使用して詳細を読むことができます:あなたはこのような何かを行うことができます。

関連する問題