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

你可能感兴趣的文章
Node-RED订阅MQTT主题并调试数据
查看>>
Node-RED通过npm安装的方式对应卸载
查看>>
node-request模块
查看>>
node-static 任意文件读取漏洞复现(CVE-2023-26111)
查看>>
Node.js 8 中的 util.promisify的详解
查看>>
node.js debug在webstrom工具
查看>>
Node.js Event emitter 详解( 示例代码 )
查看>>
Node.js GET、POST 请求是怎样的?
查看>>
Node.js HTTP模块详解:创建服务器、响应请求与客户端请求
查看>>
Node.js RESTful API如何使用?
查看>>
node.js url模块
查看>>
Node.js Web 模块的各种用法和常见场景
查看>>
Node.js 之 log4js 完全讲解
查看>>
Node.js 函数是什么样的?
查看>>
Node.js 函数计算如何突破启动瓶颈,优化启动速度
查看>>
Node.js 切近实战(七) 之Excel在线(文件&文件组)
查看>>
node.js 初体验
查看>>
Node.js 历史
查看>>
Node.js 回调函数的原理、使用方法
查看>>
Node.js 在个推的微服务实践:基于容器的一站式命令行工具链
查看>>