js prototype原型理解 Demo (1)

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>prototype</title>
</head>
<body>
<script>
    var Calculator1 = function () {

    }
    var Calculator2 = function () {

    }

    function add(x, y) {
        console.log('add')
        return x + y;
    }

    Calculator1.prototype = {
        add: function (x, y) {
            console.log('add in Calculator2.prototype')
            return x + y;
        }
    }

    /**
     * 封装私有的function,通过return的形式暴露出简单的使用名称,以达到public/private的效果。
     * @type {{add, subtract}}
     */
    Calculator2.prototype = function () {
        add = function (x, y) {
            console.log('add in Calculator2.prototype function')
            return x + y;
        }
        return {
            add: add
        }
    }();


    var _add1 = new Calculator1();
    var _add2 = new Calculator2();

    console.log(add(1, 2))  //其实用的是Calculator2内的add方法
    console.log(_add1.add(1, 3))  //私有属性
    console.log(_add2.add(1, 4)) //私有方法,通过return的形式暴露给全局
</script>
</body>
</html>

一共有三个 add方法,一个直接定义,一个在Calculator1.prototype内,一个在Calculator2.prototype function 内,最后一个通过return 的形式将add暴露给全局使用。

打印控制台:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值