本文介绍了为什么在构造函数中使用 this 关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比较代码1和代码2,哪个正确?
compare code 1 and code 2, which one is correct?
function Rectangle(height, width) { this.height = height; this.width = width; this.calcArea = function() { // why use this here? return this.height * this.width; }; }代码2我认为这很好:
function Rectangle(height, width) { this.height = height; this.width = width; calcArea = function() { return this.height * this.width; }; } 推荐答案如果不使用this,calcArea 将无法通过 Rectangle 对象访问.当你说,
If you don't use this, calcArea will not be accessible through the object of Rectangle. When you say,
this.calcArea = function () ...您在当前对象(this)中创建一个新变量,并将函数分配给它,以便对象可以访问它.
you create a new variable in the current object (this) and the function will be assigned to it, so that the object will have access to it.
试试这些语句,不管有没有this.你会更好地理解.
Try these statements, with and without this. You ll understand better.
var a = new Rectangle(1, 2); console.log(a.calcArea());更多推荐
为什么在构造函数中使用 this 关键字
发布评论