关于JS中 this的作用Insert title here\x09\x09\x09function Book(id,name,date){\x09\x09\x09this.id=id;\x09\x09\x09this.name=name;\x09\x09\x09this.date=date;\x09\x09\x09\x09\x09}\x09\x09function Collect(){\x09\x09\x09this.books=new Array();\x09\x09

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/03 17:35:08
关于JS中 this的作用Insert title here\x09\x09\x09function Book(id,name,date){\x09\x09\x09this.id=id;\x09\x09\x09this.name=name;\x09\x09\x09this.date=date;\x09\x09\x09\x09\x09}\x09\x09function Collect(){\x09\x09\x09this.books=new Array();\x09\x09

关于JS中 this的作用Insert title here\x09\x09\x09function Book(id,name,date){\x09\x09\x09this.id=id;\x09\x09\x09this.name=name;\x09\x09\x09this.date=date;\x09\x09\x09\x09\x09}\x09\x09function Collect(){\x09\x09\x09this.books=new Array();\x09\x09
关于JS中 this的作用
Insert title here
\x09
\x09\x09function Book(id,name,date){
\x09\x09\x09this.id=id;
\x09\x09\x09this.name=name;
\x09\x09\x09this.date=date;
\x09\x09\x09
\x09\x09}
\x09\x09function Collect(){
\x09\x09\x09this.books=new Array();
\x09\x09\x09
\x09\x09\x09
\x09\x09}
\x09\x09Collect.prototype.add=function(id,name,date){
\x09\x09\x09this.books[id]=new Book(id,name,date);\x09
\x09\x09}
\x09\x09Collect.prototype.show=function(){
\x09\x09\x09var book;
\x09\x09\x09var html='

';
\x09\x09\x09for(book in this.books){
\x09\x09\x09\x09html+=''
\x09\x09\x09\x09html+=''
\x09\x09\x09
\x09\x09\x09}
\x09\x09\x09html+='
';
\x09\x09\x09\x09html+=this.books[book].id; // 这里缺少了this 为什么不识别 books
\x09\x09\x09\x09html+='
';
\x09\x09\x09\x09html+=this.books[book].name; ///这里缺少了this 为什么不识别 books
\x09\x09\x09\x09html+='
'
\x09\x09\x09\x09html+=this.books[book].date; // 这里缺少了this 为什么不识别 books
\x09\x09\x09\x09html+='
'
\x09\x09\x09return html;\x09
\x09\x09}
\x09\x09var cc=new Collect();
\x09\x09cc.add(11,'三国演义','1990');
\x09\x09cc.add(12,'永恒之井','1990');
\x09\x09cc.add(13,'氏族之王','1990');
\x09
\x09\x09document.write(cc.show());
\x09

关于JS中 this的作用Insert title here\x09\x09\x09function Book(id,name,date){\x09\x09\x09this.id=id;\x09\x09\x09this.name=name;\x09\x09\x09this.date=date;\x09\x09\x09\x09\x09}\x09\x09function Collect(){\x09\x09\x09this.books=new Array();\x09\x09
this指向(指明)当前对象
你在注释里问的“ 这里缺少了this 为什么不识别 books ”
它当然不识别books,因为books是归属于Collect对象(当前对象)的,你不能跨过对象去访问对象的方法或属性(有越轨之嫌,只能通过对象本身去访问对象的方法或属性(公开的),所以要带this以指明是访问自身对象的books属性,否则,如果上下文中也没有定义过的话,books就是一个“孤魂野鬼”,无从索引,结果就是一个未定义的对象