Home  >  Article  >  Web Front-end  >  js closure and prototype

js closure and prototype

高洛峰
高洛峰Original
2016-10-12 14:28:371001browse

js闭包 和 prototype

function test(){
    var p=200;
    function q(){
        return p++;
    }
    return q;
}
var s = test();
alert(s());
alert(s());

 闭包: 在外部访问函数内部的变量:通过函数内部的函数,return 出 函数内部的变量

   原型链继承:

<script type="text/javascript">
 
//定义一个people类,包括eye和hand两个属性,和 run 的方法。
function people(ec,hc){
    this.eye = ec;
    this.hand = hc;
}  
people.prototype.run = function(){
    console.log("人类用" + this.hand + "的腿跑步");
}
 
//定义chin类,调用people 的 call 方法,继承people的 eye 和 hand 属性。
function chin(ec,hc){
    people.call(this,ec,hc);
}
//创造people类的原型副本(此时该原型副本的构造方法是指向people的,所以需要修正该构造方法,改成chin)
var _prototype = Object.create(people.prototype);
_prototype.constructor = chin;
//把chin的原型赋值给 _prototype 。此时 chin 即继承了people的 run方法。但是没有改变people的原型。
chin.prototype = _prototype;
 
//给chin类增加一个 sw方法。
chin.prototype.sw = function(){
    console.log("中国人游泳很厉害");
}
 
var s = new chin("黑眼睛","黄皮肤");
 
console.log(s);
console.log(s.eye);
console.log(s.run());
console.log(s.sw());
 
var p = new people("蓝眼睛","黑皮肤");
console.log(p);
</script>

 结果如下:

js closure and prototype

call:

function a(data){
    alert(this.q + data);
}
 
var s = {
    q:100
}
//call的第一个参数是 this,当传入 s 时,即把this 改成了 s ,可以访问 s 内部的变量q 。
a.call(s, 1);

  结果 alert 101

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn