How to call a function when using a property?

When I change a property in a JavaScript class, I want to enter the console when an old deprecated property is used.

eg.

var app = function() {
    this.oldvar = function() { console.log('oldvar is old!'); return myapp.newvar; };
    this.newvar = 'Hello world!';
}

var myapp = new app();

alert(myapp.oldvar);

My example will not work, because a string representation is output oldvar, and the function will not actually be called.

I want him to alert()think that he is using the old property, but the "extra" code will be executed in the function.

I do not want to call oldvar as a function. I want my code to try, but alert()as a string.

Is it possible?

+4
source share
3 answers

You can define getter for appas follows:

var app = function () {
    this.newvar = 'Hello world!';
};

app.prototype = {
    get oldvar() {
        console.log('oldvar is old!');
        return this.newvar;
    }
};

var myapp = new app();

alert(myapp.oldvar);

Node.js v0.10.32 JSFiddle Chrome , , . ECMA Script, . Mozilla Developer Docs .

prototype app. , , app - . , , , :

var app = function () {
    this.newvar = 'Hello world!';
};

Object.defineProperty(app.prototype, 'oldvar', {
    get: function () {
        console.log('oldvar is old!');
        return this.newvar;
    }
});

var myapp = new app();

alert(myapp.oldvar);

, get ters . , delete JavaScript, .. delete app.prototype.oldvar;.

+4

, oldvar , .

, ECMAScript 5 ( , .. IE9)

:

var app = {
    newvar: 'Hello world!'
};

Object.defineProperty(app, 'oldvar', {
    get: function() {
        console.log('oldvar is old!');
        return this.newvar;
    }
});

: http://javascriptplayground.com/blog/2013/12/es5-getters-setters/

+2

You just need to call the oldVar property as a function: Use alert(myapp.oldvar());

0
source

All Articles