为什么在构造函数中使用 this 关键字

编程入门 行业动态 更新时间:2024-10-27 06:22:25
本文介绍了为什么在构造函数中使用 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 关键字

本文发布于:2023-06-08 21:23:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589302.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   关键字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!