1. 程式人生 > >js中閉包作用舉例

js中閉包作用舉例

efi xiaomi cti log 舉例 ons fine ole undefine

模擬實現類的私有屬性

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中閉包作用舉例