为何JavaScript构造函数中需添加this.recall=recall才能调用方法?
为什么需要
this.recall=recall这行代码? 嘿,这个问题刚好戳中了JavaScript里this绑定规则和构造函数实例化的核心逻辑,我来给你拆解明白:
1. 移除那行代码后为啥报错?
你定义的recall是一个全局函数,但当你用new Private()创建man实例时,这个实例本身并没有recall这个方法。JS引擎查找属性时会先从实例本身找,找不到再往上走原型链,最后还是找不到recall,自然会抛出“recall is not a function”的错误。
2. this.recall=recall到底做了什么?
这行代码的作用是把全局的recall函数赋值给当前实例的recall属性。简单说就是给每个Private实例“安装”了recall方法,这样当你调用man.recall()时,JS引擎能在man实例上找到这个方法,才能正常执行。
3. 更关键的是this的指向问题
你肯定注意到recall函数里用到了this.height这类属性——这里的this指向完全由调用方式决定:
- 当你通过
man.recall()调用时,this会自动绑定到man这个实例,所以能访问到实例上的height、weight、age属性; - 如果直接调用全局的
recall(),this会指向浏览器的全局对象window,那自然找不到这些实例属性,代码一样会报错。
额外优化:用原型方法更高效
其实不用给每个实例都单独赋值recall方法,把它放到Private的原型上,所有实例都能共享这个方法,更节省内存:
function recall (){ document.write('the height is:'+ this.height+'<br>'); document.write('the weight is:'+ this.weight+'<br>'); document.write('the age is:'+ this.age+'<br>'); } function Private(height,weight,age){ this.height=height; this.weight=weight; this.age=age; } // 把recall挂载到原型上,所有实例共享 Private.prototype.recall = recall;
或者直接在原型上定义函数更直观:
function Private(height,weight,age){ this.height=height; this.weight=weight; this.age=age; } Private.prototype.recall = function(){ document.write('the height is:'+ this.height+'<br>'); document.write('the weight is:'+ this.weight+'<br>'); document.write('the age is:'+ this.age+'<br>'); }
这种写法更贴合JavaScript的原型继承逻辑,性能也更好~
内容的提问来源于stack exchange,提问作者Caleb Hyun
相关产品推荐
相关产品推荐

