关于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/07/30 07:26:35
![关于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](/uploads/image/z/10605614-14-4.jpg?t=%E5%85%B3%E4%BA%8EJS%E4%B8%AD+this%E7%9A%84%E4%BD%9C%E7%94%A8Insert+title+here%5Cx09%5Cx09%5Cx09function+Book%28id%2Cname%2Cdate%29%7B%5Cx09%5Cx09%5Cx09this.id%3Did%3B%5Cx09%5Cx09%5Cx09this.name%3Dname%3B%5Cx09%5Cx09%5Cx09this.date%3Ddate%3B%5Cx09%5Cx09%5Cx09%5Cx09%5Cx09%7D%5Cx09%5Cx09function+Collect%28%29%7B%5Cx09%5Cx09%5Cx09this.books%3Dnew+Array%28%29%3B%5Cx09%5Cx09)
关于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\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就是一个“孤魂野鬼”,无从索引,结果就是一个未定义的对象