栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

JavaScript不使用prototype和new实现继承机制

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript不使用prototype和new实现继承机制

此方法并非笔者原创,笔者只是在前辈的基础上,加以总结,得出一种简洁实用的Javascript继承方法。

      传统的Javascript继承基于prototype原型链,并且需要使用大量的new操作,代码不够简洁,可读性也不是很强,貌似还容易受到原型链污染。

      笔者总结的继承方式,简洁明了,虽然不是最好的方式,但希望能给读者带来启发。

      好了,废话不多说,直接看代码,注释详尽,一看就懂~~~

复制代码 代码如下:
 
 
 Object.prototype.clone = function(){
     var _s = this,
         newObj = {};
     _s.each(function(key, value){
         if(Object.prototype.toString.call(value) === "[object Function]"){
             newObj[key] = value;
         }
     });
     return newObj;
 };
 
 Object.prototype.each = function(callback){
     var key = "",
         _this = this;
     for (key in _this){
         if(Object.prototype.hasOwnProperty.call(_this, key)){
             callback(key, _this[key]);
         }
     }
 };
 
 Object.prototype.extend = function(ext){
     var child = this.clone();
     ext.each(function(key, value){
         child[key] = value;
     });
     return child;
 };
 
 Object.prototype.create = function(){
     var obj = this.clone();
     if(obj.construct){
         obj.construct.apply(obj, arguments);
     }
     return obj;
 };
 
 
 var Animal = {
     construct: function(name){
         this.name = name;
     },
     eat: function(){
         console.log("My name is "+this.name+". I can eat!");
     }
 };
 
 var Bird = Animal.extend({
     eat: function(food){
         console.log("My name is "+this.name+". I can eat "+food+"!");
     },
     fly: function(){
         console.log("I can fly!");
     }
 });
 
 var birdJim = Bird.create("Jim"),
     birdTom = Bird.create("Tom");
 birdJim.eat("worm");  //My name is Jim. I can eat worm!
 birdJim.fly();  //I can fly!
 birdTom.eat("rice");  //My name is Tom. I can eat rice!
 birdTom.fly();  //I can fly!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/104826.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号