zoukankan      html  css  js  c++  java
  • JS类定义方式

    // 方法1 对象直接量

    var obj1 = {
        v1 : "",
        get_v1 : function() {
            return this.v1;
        },
        set_v1 : function(v) {
            this.v1 = v;
        }
    };
    obj1.set_v1('hello1');
    alert(obj1.get_v1());

    // 方法2 定义函数对象

    var Obj = function() {
        var v1 = "";
        this.get_v1 = function() {
            return this.v1;
        };
        this.set_v1 = function(v) {
            this.v1 = v;
        }
    };
    var obj2 = new Obj();
    obj2.set_v1('hello2');
    alert(obj2.get_v1());

    // 方法3 原型继承

    var Obj3 = new Function();
    Obj3.prototype = {
        v1 : "",
        get_v1 : function() {
            return this.v1;
        },
        set_v1 : function(v) {
            this.v1 = v;
        }
    };
    var obj3 = new Obj();
    obj3.set_v1('hello3');
    alert(obj3.get_v1());

    // 方法4 工厂模式

    function loadObj() {
        var tmp = new Object();
        tmp.v1 = "";
        tmp.get_v1 = function() {
            return tmp.v1;
        };
        tmp.set_v1 = function(v) {
            tmp.v1 = v;
        };
        return tmp;
    }
    var obj4 = loadObj();
    obj4.set_v1('hello4');
    alert(obj4.get_v1());
  • 相关阅读:
    19. vue的原理
    18.jwt加密
    17.vue移动端项目二
    16.vue-cli跨域,swiper,移动端项目
    15.vue动画& vuex
    14.vue路由&脚手架
    13.vue组件
    12.vue属性.监听.组件
    11.vue 数据交互
    从尾到头打印链表
  • 原文地址:https://www.cnblogs.com/shockerli/p/js-class-define-type.html
Copyright © 2011-2022 走看看