代码:
<!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暴露给全局使用。
打印控制台: