您的位置:首页 > Web前端 > JavaScript

Javascript定义函数和this使用

2009-12-10 16:15 316 查看
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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐