在使用backbone时,每一种类型都是通过继承的方式得来的,如视图:

1
Backbone.View.extend({})

其他的包括模型、路由

js实现继承的一种方式

backbone实现继承的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
参数:
protoProps: 原型属性,添加到prototype属性,使用new新建的对象都含有此属性
staticProps: 静态属性,添加到function本身的属性
返回值:
child: function;
*/
BaseObject.extend = function(protoProps, staticProps) {
var parent = this;
var child;

//如果有传入原型属性、并且包含有constructor参数,则使用constructor作为要返回的函数
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {//否则,使用BaseObject作为要返回的函数
child = function() {
if (!(this instanceof child)) //兼容`new` 和 `不用new` 两种场合
return new child(arguments);
else
return parent.apply(this, arguments);
};
}

//使用underscore中的extend方法,将BaseObject、staticProps的属性添加到child中
_.extend(child, parent, staticProps);

var Surrogate = function() { this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;//为child赋值新的prototype

if (protoProps) _.extend(child.prototype, protoProps);//将传入的protoProps添加到child的原型中

child.__super__ = parent.prototype;//保存基础的原型,以备使用

return child;
}

使用方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
BaseObject = function(){
console.log('i am BaseObject');
}
BaseObject.prototype = {
sayHello:function(){
console.log('hello ' + this.name)
}
}

var People = BaseObject.extend({name:'world'});
var p = new People();
p.sayHello();

==>
i am BaseObject
hello world

本文地址: http://gehaiqing.com/2017/02/14/js-backbone-extend/