关于Javascript定义函数和this使用的两点注意的地方

来源:互联网 发布:linux硬件级虚拟机 编辑:程序博客网 时间:2024/05/01 22:32

 总结:
一、函数定义:
1.在实例和类上都可以直接定义函数
2.不能在实例上使用prototype定义函数,只能在类上使用prototype定义函数
3.类上直接定义的函数不能使用this访问对象的属性
4.在类的prototype上建立的函数可以用this,在类内部定义的函数可以使用this,在对象实例上建立的函数额可以this

 

  1. window.alert=function (msg) 
  2. document.write(msg+"<br>"); 
  3. function say() 
  4. this.f="props"
  5. this.func3=function(){alert("f3,"+this.f);} 
  6. say.func1=function(){alert("func1,"+this.f);}; //Error,类上直接定义的函数,不能使用this 
  7. say.prototype.func2=function(){alert("func2,"+this.f);} 
  8. say.func1(); 
  9. (new say()).func2(); 
  10. say.func2(); //Error, 在用prototype定义的函数,必须实例化对象才能调用 
  11. say.func3(); //Error,在类上定义的函数,必须实例化才能调用 
  12. (new say()).func3(); 
  13. var obj={ 
  14. fld1:10, 
  15. func1:function(msg){alert(msg);}, 
  16. func4:function(){alert(this.fld1);} 
  17. obj.prototype.func=function(){alert("func");}; //Error 实例对象上不能使用prototype定义对象 
  18. obj.func2=function(){alert("func2,"+this.fld1);}; //ok,实例上直接定义的函数可以使用this,访问对象的属性 
  19. alert(obj.fld1); 
  20. obj.func1("func1"); 
  21. obj.func2(); 
  22. obj.func4(); 
原创粉丝点击