<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>JS封装类或对象</title>
<script>
var Person = (function () {
//静态私有属性方法
var _place = "shen zhen";
function _say(name) {
console.log(name + " is live in " + _place);
}
function _walk() {
console.log("i am walking");
}
//构造函数
function _person(name, age) {
var _this = this;
//构造函数安全模式,避免创建时候丢掉new关键字
if (_this instanceof _person) {
//共有属性, 方法
_this.place = _place;
_this.say = function () {
_say(name)
}
_this.walk = _walk;
_this.age = age + 12;
} else {
return new _person(name, age);
}
}
return _person;
})();
var p1 = new Person("zhangsan", 12);
p1.say(); //zhangsan is live in shen zhen
console.log(p1.age); //24
p1.walk(); //i am walking
console.log(p1.place) //shen zhen
</script>
</head>
<body>
</body>
</html>