开发者

Method chaining in javascript

This working code is 开发者_StackOverflow中文版using Sproutcore:

person = SC.Object.create({
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: function() {
        return this.get('firstName') + " " + this.get('lastName');
    }.property()

});

console.log(person.get('fullName')); // "Foo Bar"

I wonder where property() is declared and how they have made this to work. When I try to reconstruct this without the SC class, it gives me:

TypeError: Object function () {
        return this.get('firstName') + " " + this.get('lastName');
    } has no method 'property'

How does the code looks like to make it work?


Sproutcore is extending the function prototype.

Function.prototype.property = function() { /* code here */ };

The specific code use by sproutcore is at https://github.com/sproutcore/sproutcore/blob/master/frameworks/runtime/core.js#L908

SC.mixin(Function.prototype, 
//...snip...

property: function() {
    this.dependentKeys = SC.$A(arguments) ;
    var guid = SC.guidFor(this) ;
    this.cacheKey = "__cache__" + guid ;
    this.lastSetValueKey = "__lastValue__" + guid ;
    this.isProperty = YES ;
    return this ;
  },
//snip
);

In their case, they are using their own mixin method, but the concept is the same: extending the prototype


Presumably, Sproutcode has modified Function.prototype to include a property function.

You could just look at the source code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜