1函数中this作用域
this根据当前环境来决定作用域,可以使用call和apply的方法来改变当前的this指向
<script> var name = "global"; function fn(){ console.log(this.name); }; fn();//函数申明式,this指向全局,"global" var obj ={ name:"object", say:function(){ console.log(this.name); } } obj.say();//对象中调用,this指向当前对象,"object" function Person(){ this.name="person"; this.say=function(){ console.log(this.name); } } var p = new Person(); p.say();//构造函数中调用指向当前构造函数,“person” </script>
2函数的继承方法
构造函数和函数原型的继承
在构造函数里调用call,实现继承
<script> function Parent(){ this.name = "zzz"; this.age = 233; }; function Child(){ Parent.call(this); this.favor = "dance"; } var p = new Parent(); var c = new Child(); console.log(p);//{name: "zzz", age: 233} console.log(c);//{name: "zzz", age: 233, favor: "dance"} </script>
原型链的继承
<script> function Parent(){ this.name = "zzz"; this.age = 23; }; function Child(){ this.favor = "dance"; } Parent.prototype.id=233; Child.prototype = new Parent(); var c = new Child(); console.log(c.id);//233 </script>