javascropt oop与闭包

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>闭包</title>
</head>

<body>
<script>
// JavaScript Document

// var Person=function(name,age){
// this.name=name;
// this.age=age;
// this.say=function(){
// console.info('hello')
// }
// }
// Person.prototype={
// Person:function(){
//
// },
// hello:function(){
// console.info(this.age+' '+this.name)
// }
// }
// var p=new Person();
// p.say();
//
// var p1=new Person('zhangsan',19);
// p1.hello();


var Person=function(){
var id=1;//private
this.name='';//public
//闭包访问私有变量
this.say=function(){
return function(){
return id;
};
}
}
Person.age=19;//静态变量 可以通过类或对象访问
/**
* 通过原型扩展属性和方法
* @type {{}}
*/
Person.prototype={
address:'',
hello:function(){
console.info('hello');
}
}

//实例化对象
var person=new Person();
console.info('类变量:'+Person.age)
console.info('私有变量:'+person.id);//访问不到 underfined
console.info('使用闭包访问 私有变量:'+person.say()())
person.name='张三';
person.address='重庆';
console.info(person)
console.info(new Person().hello())


</script>

</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值