博客
关于我
让JS写的更接近OOP
阅读量:456 次
发布时间:2019-03-06

本文共 1964 字,大约阅读时间需要 6 分钟。

 

下面这段代码就是利用JS原型对象,来实现的类的继承DEMO 

 

$ 为jquery对象

////公共方法//  $.oop.newClass=function newClass(obj) {//     function create() {//         if (obj != null)//             return obj();//     }//     var c = new create();//     return c;// }//人var person = $.oop.newClass(function () {    //构造函数    function person() {    }    //公有属性    person.prototype.age = 15;    //公有函数    person.prototype.eat = function () {        alert("我会吃");    };    return person;});//程序员var programMonkey = $.oop.newClass(function () {    //构造函数    function programMonkey() {    } programMonkey.prototype = person.prototype;//继承    programMonkey.prototype.skill = "asp.net";    programMonkey.prototype.work = function () {        alert("我会加班");    }    return programMonkey;});var pm = new programMonkey();//人的函数pm.eat();//程序猿的函数pm.work();//输出属性alert("人家才" + pm.age + "岁,我是一个" + pm.skill + "猿");

 

因为JS一些特性实现一个多态也非简单

 

//共用函数//$.oop.newClass = function (obj) {//    function Create() {//        if (obj != null)//            return obj();//    }//    var c = new Create();//    return c;//}var iPerson = $.oop.newClass(function () {    //构造函数    function person() {    }    person.prototype.name;    person.prototype.iq;    person.prototype.eat;    return person;});//程序员var programMonkey = $.oop.newClass(function () {    //构造函数    function programMonkey() {    } programMonkey.prototype = iPerson.prototype ;//继承    return programMonkey;});//设计湿var designer = $.oop.newClass(function () {    //构造函数    function designer() {    } designer.prototype = iPerson.prototype ;//继承    return designer;});var inputValue = "程序员";var ip = new iPerson();if (inputValue == "程序员") {    ip = new programMonkey();    ip.iq = 0;    ip.eat = function (msg) {        alert(msg + "吃香蕉")    }    } else if (inputValue == "设计湿") {    ip = new designer();    ip.iq = 100;    ip.eat = function (msg) {        alert(msg + "吃香蕉")    }}ip.name = inputValue; ip.eat("我是"+ip.name+"  智力"+ip.iq+" ");

 

根据不同的input Value会执行相应的 eat函数

 

转载地址:http://zrofz.baihongyu.com/

你可能感兴趣的文章
nginx 禁止以ip形式访问服务器
查看>>
Nginx 结合 consul 实现动态负载均衡
查看>>
Nginx 负载均衡与权重配置解析
查看>>
Nginx 负载均衡详解
查看>>
nginx 配置 单页面应用的解决方案
查看>>
nginx 配置https(一)—— 自签名证书
查看>>
nginx 配置~~~本身就是一个静态资源的服务器
查看>>
Nginx 配置服务器文件上传与下载
查看>>
Nginx 配置清单(一篇够用)
查看>>
Nginx 配置解析:从基础到高级应用指南
查看>>
Nginx 集成Zipkin服务链路追踪
查看>>
nginx 集群配置方式 静态文件处理
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
Nginx+Tomcat实现动静分离
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>