2017-05-10 3 views
3

Je souhaite rendre une propriété invocable ou non. Ainsi, par exemple:Rendre une propriété invocable ou non

function Test() { 
    var obj = { someString: 'here is text' }; 

    Object.defineProperty(obj, 'string', { 
    get: function() { 
     return obj.someString; 
    }, 
    set: function() { 
     return function(val) { 
     obj.someString = val; 
     } 
    } 
    }); 

    return obj; 
} 

var test = new Test(); 

De cette façon, je pouvais faire:

test.string // initially returns 'here is text'

test.string('new text here') // sets obj.someString to 'new text here'

test.string // returns 'next text here'

Le code ne ci-dessus ne fonctionnent actuellement la façon dont je veux. Est-il possible de faire quelque chose comme ça en JavaScript? Soit en utilisant Object.defineProperty ou pas

+1

Quel est le cas d'utilisation de ce comportement? –

+0

@shambalambala J'ai fait une meilleure question pour cela ici: http://stackoverflow.com/questions/43923053/how-to-make-a-property-method-invokable-or-not – georgej

Répondre

0

Je ne suis pas sûr que ce soit possible. Au lieu de cela, vous pouvez le faire conditionnelle si un paramètre de fonction est définie et si elle est pas la fonction de lecture de la propriété:

function Test() { 
    var obj = { 
    someString: 'here is text', 
    string: function(val) { 
     if(val == undefined) { // If the val parameter was not defined 
     return this.someString; // Just return the property someString 
     } else { // Otherwise, 
     this.someString = val; 
     } 
    } 
    }; 
    return obj; 
} 

var Tmp = new Test(); 
console.log(Tmp.string()); // This outputs 'here is text' 
Tmp.string('New text!'); // This sets someString to 'New Text!' 
console.log(Tmp.string()); // This outputs 'New Text!' 

La principale différence entre cela et ce que vous vouliez est qu'au lieu de intitulant Tmp.string pour récupérer la valeur, vous appelez Tmp.string().

Voici mon jsfiddle

0

Vous pouvez utiliser la syntaxe ES6:

class Test{ 
    constructor(){ 
    this.someString = "here is text"; 
    } 

    get string(){ 
    return this.someString; 
    } 

    set string(val){ 
    this.someString = val 
    } 
}