简体   繁体   中英

Inject variables of parent context in function - JavaScript

I'm developing a micro MV* Framework for JavaScript and came upon the idea to introduce computed properties like it's done in Ember.js

What I basically want is something like this:

_defaults: {
    firstEarning: 5,
    secondEarning: 1200.75,
    paycheck: function(firstEarning, secondEarning) {
        return firstEarning + secondEarning;
    }.inject('firstEarning', 'secondEarning')
}

When I want to retrieve paycheck then the values of firstEarning and secondEarning should be injected into the function.

I tried to extend the Function prototype, but realized that I don't have the context pointing to the object where _defaults lives.

I tried to understand what Ember.js did to achieve this, but I didn't really get it.

Has anybody here an idea how to achieve this?

... I think you're really over-thinking this.

Just use this :

_defaults: {
    firstEarning: 5,
    secondEarning: 1200.75,
    paycheck: function() {
        return this.firstEarning + this.secondEarning;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM