博客
关于我
让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/

你可能感兴趣的文章
NFS的安装以及windows/linux挂载linux网络文件系统NFS
查看>>
NFS的常用挂载参数
查看>>
NFS网络文件系统
查看>>
NFS远程目录挂载
查看>>
nft文件传输_利用remoting实现文件传输-.NET教程,远程及网络应用
查看>>
NFV商用可行新华三vBRAS方案实践验证
查看>>
ng build --aot --prod生成文件报错
查看>>
ng 指令的自定义、使用
查看>>
nghttp3使用指南
查看>>
Nginx
查看>>
nginx + etcd 动态负载均衡实践(三)—— 基于nginx-upsync-module实现
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>