javascript是一门比较难精通的语言,缘由是其余语言提供机制,javascript提供方法。
在我看来,语言如java,python比较好学的语言有一个特色:关键字多。java提供extends,implements,以及特定的包管理机制。python特殊的文本结构,大量API等。这些语言可使初学者快速上手,由于大多数需求的知足都是靠机制。语言提供的关键字,库管理,API。一句话就是你们写的代码都同样,思路同样,代码就同样(或差异不大,由于设计模式的存在,有结构差别,但底层结构也相同)。
另外一种语言提供做用域,内存布局,语言自己的默认设置等。这种语言如c,c++,javascript,函数式语言。自己是带有一种编译器或解释器的感受。就是用户身在其中,须要知道一些编译器开发人员才须要的知识。就以javascript来讲吧,要想实现继承,你就得了解解释器在读取一个对象的属性的过程当中是怎么寻找的(原型链)。c语言:宏,你得了解预处理器;全局变量,链接器;C++:struct和class的区别,vptr,多继承等。
说这么多,只是想为本身花了半年学javascript的痛苦吐槽一下,并无比较语言的意思,莫喷!java那种思路一下,代码差异不大的优点在企业级开发中才能体现,so i love java!绝没有瞧不起的意思。javascript
以java为例:java
class Parent{python
String name; //private field Parent(String name){ this.name = name; }
}c++
class Child{设计模式
int id; //private field Child(String name,int id){ super(name); this.id = id; }
}函数
继承的重点:布局
1.Child实例化以前,Parent必须实例化
2.Child对象可使用Parent对象的方法和属性
3.Child能够添加本身的方法,若是方法名相同,则覆盖Parent的方法
4.Child能够添加本身的静态方法,能够继承Parent的父类方法this
这也是网上比较多的继承方法(类式继承):prototype
function Parent () { this.ParentValue = true; //private field } Parent.staticP = 1; Parent.prototype.getValue = function () { return this.ParentValue; } function Child () { this.ChildValue = true; //private field } Child.prototype = new Parent(); Child.prototype.getValue = function () { return this.ChildValue; } Child.staticC = 1;
这种方式不能知足上面的4个条件:
1.知足,可是不是彻底相同。Parent在Child定义时就已经实例化了,Parent实例化太超前了,致使全部Child对象同享一个Parent实例,若是一个Child对象改变了Parentvalue,全部Child对象都发生改变。
2.知足
3.知足
4.不知足
因此说基本知足2.5条吧设计
function Parent () { this.ParentValue = true; //private field } Parent.staticP = 1; Parent.prototype.getValue = function () { return this.ParentValue; } function Child (p,c) { Parent.call(this,p); this.ChildValue = c; //private field } Child.staticC = 1; inheritPrototype(Parent,Child); Child.prototype.getValue = function () { return this.ChildValue; } function inheritPrototype (Parent,Child) { merge(Parent,Child); //将Parent上的属性放置到Parent上 var p = inheritObject(Parent.prototype); p.constructor = Child; return p; } function inheritObject (o) { function F(){} F.prototype = o; return new F(); } //将Parent上的属性放置到Parent上 function merge (dist,source) { for(attr in source){ if(source.hasOwnProperty(attr)){ if(!dist.hasOwnProperty(attr)){ dist[attr] = source[attr]; } } } }
我参考Backbone的实现
Backbone依赖Underscore
function Parent () { this.ParentValue = true; //private field } Parent.staticP = 1; function Child (p,c) { Parent.call(this,p); this.ChildValue = c; //private field } function extend(Parent,Child,protoProps,staticProps){ _.extend(Child, Parent, staticProps); Child.prototype = _.create(Parent.prototype, protoProps); Child.prototype.constructor = Child; return Child; } extend(Parent,Child,{ getValue: function() { return this.ParentValue; } }, { staticC: 1 }); 是否是更方便呢!