首页 > 代码库 > js中闭包作用举例

js中闭包作用举例

模拟实现类的私有属性

function Boy(name){

  this.name = name;

  var sex = ‘boy‘;

  this.saySex = function(){

    console.log("my sex is "+sex)
  };

}

var xiaoming = new Boy(‘xiaoming‘);

console.log(xiaoming.name);

console.log(xiaoming.sex);

xiaoming.saySex();
VM344:16 xiaoming
VM344:18 undefined
VM344:9 my sex is boy

js中闭包作用举例