Backbone 模型中的 `this` 是什么?

What is `this` inside a Backbone model?

我正在学习一些 Backbone,但我对模型内部的 this 感到困惑。

Person = Backbone.Model.extend({
    initialize: function() {
        console.log('hello world');
        this.bind("change:name", function() {
            console.log(this.get('name') + " is now the value for name");
        });
        this.bind('invalid', function( model, error ) {
            console.error(error);
        });
    },
    defaults: {
        name: "Bob Hope",
        height: "unknown"
    },
    validate: function ( attributes ) {
        if( attributes.name == 'Joe' ) {
            return "Uh oh, you're name is Joe!";
        }
    }
});
var person = new Person();
person.set({name: "Joe", height:"6 feet"}, {validate:true});
console.log(person.toJSON());

this.bind 发生了什么事?什么是 change:nameinitializedefaults 只是 javascript 对象内部的方法吗?

this里面initialize是模型的实例。

.bind.on method inside backbone.Events 模块的别名,它允许您在对象上绑定事件处理程序

change:name 只是事件名称,它允许您跟踪名为 'name'.

的模型属性的变化

initialize 是一个构造函数方法,当您实例化模型时将首先调用它。

defaults是设置默认模型属性的对象(也可以是函数)

所以initializedefaults确实是对象内部的方法(除了defaults也可以是属性),但是它们对backbone。并且该对象扩展了 Backbone.Model 的所有其他方法和属性,这使其成为一个功能模型。

阅读更多内容 backbone docs