专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »Javascript教程 » javascript定义函数:关于Javascript定义函数和this使用的两点注意的地方 »正文

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

来源: 发布时间:星期二, 2008年10月7日 浏览:191次 评论:0

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


window.alert=function (msg)
{
document.write(msg+"<br>");
}

function say()
{
this.f="props";
this.func3=function(){alert("f3,"+this.f);}
}

say.func1=function(){alert("func1,"+this.f);}; //Error,类上直接定义的函数,不能使用this
say.prototype.func2=function(){alert("func2,"+this.f);}
say.func1();
(new say()).func2();
say.func2(); //Error, 在用prototype定义的函数,必须实例化对象才能调用
say.func3(); //Error,在类上定义的函数,必须实例化才能调用
(new say()).func3();

var obj={
fld1:10,
func1:function(msg){alert(msg);},
func4:function(){alert(this.fld1);}
}
obj.prototype.func=function(){alert("func");}; //Error 实例对象上不能使用prototype定义对象
obj.func2=function(){alert("func2,"+this.fld1);}; //ok,实例上直接定义的函数可以使用this,访问对象的属性

alert(obj.fld1);

obj.func1("func1");
obj.func2();

obj.func4();

相关文章

读者评论

  • 共0条 分0页

发表评论

  • 昵称:
  • 内容: