闭包的好处:
1.不会污染全局环境;
2.可以进行形参的记忆,减少形参的个数,延长形参生命周期;
function add(x) {
return function(y) {
return (x+y);
}
}
var sum = add(2);
sum(5);//结果为 7
3.方便进行模块化开发;
var module = (function() {
var name = '123';
function init() {
console.log(name);
}
return {
getname:init
}
})()
module.getname();//结果为 123;
继承:一个构造函数继承另一个构造函数中的方法;可以省去大量的重复。
function Man(name,age) {
this.name = name; this.age = age;
}
var person = new Man('tom',19);
function Woman(name,age) {
this.sex = 'woman';
Man.call(this,name,age);
}
Woman.prototype = Man.prototype;
var person1 = new Woman('july',20);
person1.name//结果为 july
person1.age //结果为 20
person1.sex //结果为 woman
原型链查找:进行方法调用的时候,会先在实例自身上找,如果没有就去该实例的原型上找。
function People() {
this.name = 'a People';
}
People.prototype.say = function() {
this.age = '10';
console.log(this.name,this.age);
}
var person = new People();
person.say();