现在位置: 首页  >  编程技术  >  JS
js封装组件模板
0 1375
var Tool = function (id, name, price) {

    /****** 私有属性 ******/
    var that=this; // that被赋值为当前对象this,这样私有方法就可以通过that访问共有属性和方法了。
    var goodsName = '',goodsPrice = 0;

    /****** 对象共有属性 ******/
    this.goodsId = id+10;

    /****** 私有方法 ******/
    function checkGoodsId() {
        // 私有方法不能访问公共属性,this只有在实例化后调用才指向自身,在函数内直接运行是指向的Window,这里调用that,that已经被赋值为当前对象的this。
        // console.log(this.goodsId , that.goodsId); // 这里的 this.goodsId 为undefined
        return id>20;
    }


    /****** 特权方法 --- 可操作私有属性的方法 ******/
    this.getName = function () {return goodsName};
    this.setName = function (n) {goodsName=n};
    this.getPrice = function () {return goodsPrice};
    this.setPrice = function (p) {goodsPrice=p};

    /****** 对象共有方法 ******/
    // 将私有方法公开
    function printId(){
        console.log(this.goodsId)
    }
    this.printId=printId; // 实例化后可正常调用

    // 直接定义
    this.printNameAndPrice = function () {
        // ...
        if (checkGoodsId()){
            console.log( goodsName + ',' + goodsPrice );
        }else{
            console.log('id<=20的产品不公开价格信息');
        }
    };

    this.test = function () {
        let that=this;
        let opt={
            a:'aA',
            b:function () {
                console.log(this.a,that.goodsId);
            }
        };
        console.log(opt.b()); // aA
    };


    /****** 安全模式 ******/
    if(this instanceof Tool){
            // 这里面写初始化代码
        // 比如 let a = new Tool();
        this.setName(name);
        this.setPrice(price);
    }else{
        // 比如 let a = Tool();
        // 如果不这么做,let a = Tool(); 中 Tool() 只会执行函数返回函数的返回值(此函数没有返回值,所以会返回undefined)
        return new Tool(id, name, price);
    }

};

/****** 实例化 ******/
let a=new Tool(30,'apple',200);

/****** 拓展原型属性 ******/
Tool.prototype.pay=function(){
    console.log('滴,已付款');
};
// 已实例化的对象也可调用原型拓展后的属性
a.pay();


 评论
 站内搜索