JavaScript中去掉原型模式中this的疑问??

查看:85
本文介绍了JavaScript中去掉原型模式中this的疑问??的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

function Person(name){
   this.name=name;
}
Person.prototype.getName=function(){
return this.name;
}
//调用函数
var person=new Person("Nicholas");
alert(person.getName());

疑问:
同一个函数,为啥在去掉this(原型模式中的this)后代码如下:

Person.prototype.getName=function(){
    return name;
}

出现如下的错误:

Test3.html:102 Uncaught ReferenceError: age is not defined

this不去掉的话,就会输出Nicholas;

解决方案

原型和构造函数中的this都指向new出来的对象,构造函数中的代码是为name赋值,而原型中的代码是访问name的值,去掉this就是在全局环境中找name了,找不到所以返回undefined。

这篇关于JavaScript中去掉原型模式中this的疑问??的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆