轻松理解this关键字

一、Java中的this

在Java编程语言中,this关键字是一个引用变量,它指向当前对象。this关键字通常用于以下几种情况:

1、区分实例变量和局部变量

当方法的参数或局部变量与实例变量同名时,可以使用this关键字来明确地引用实例变量。例如:

创建Student类:

public class Student {
    private int age;

    public void showAge(int age){
        System.out.println("不使用this关键字:"+age);
        System.out.println("使用this关键字:"+this.age);
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 测试方法:

public class Test5 {
    public static void main(String[] args) {
        Student student = new Student();
        student.setAge(18);
        student.showAge(15);
    }
}

测试结果:

在Student类中的showAge()方法中传递的age的值为15;

在测试方法中使用setAge(18)方法设置student的成员变量age值为18;

通过打印结果可以看出,age代表showAge()方法中的局部变量,this.age代表的是成员变量。

2、调用当前对象的其他方法

可以使用this关键字在一个方法内部调用同一个类中的其他方法。例如:

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int addAndDouble(int a, int b) {
        int sum = this.add(a, b); // 使用this调用另一个方法
        return 2 * sum;
    }
}

3、返回当前对象

在某些设计模式中,如链式调用(method chaining),可以使用this关键字返回当前对象,以便连续调用多个方法。例如:

public class FluentPerson {
    private String name;
    private int age;

    public FluentPerson setName(String name) {
        this.name = name;
        return this; // 返回当前对象
    }

    public FluentPerson setAge(int age) {
        this.age = age;
        return this; // 返回当前对象
    }
}

4、构造器中调用另一个构造器

在一个类的构造器中,可以使用this关键字调用同一个类中的另一个构造器。这称为构造器重载。例如:

public class Rectangle {
    private int width;
    private int height;

    public Rectangle() {
        this(0, 0); // 调用另一个构造器
    }

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }
}

5、传递当前对象作为参数

有时需要将当前对象传递给其他方法或构造器,可以使用this关键字。例如:

public class MyClass {
    public void printObject() {
        System.out.println(this); // 打印当前对象
    }
}

总结来说,this关键字在Java中主要用于引用当前对象,以解决命名冲突、调用其他方法、返回当前对象以及在构造器中调用其他构造器等场景。

6、结合内存图解释this

因为是新创建的student对象调用的showAge()方法,所以this的值表示student对象,而this.age就是student.age。


二、JavaScript中的this

this用于引用当前正在执行的函数或方法所属的对象。

下述以点击元素跟换背景颜色为例:

dom.js:

//使用dom操作中的document.getElementsByClassName("bb")获取名为
var array = document.getElementsByClassName("bb");
//在控制台打印结果
console.log(array);
//循环遍历元素
for(var j = 0;j < array.length;j++){
    console.log(array[j])
    //为每个元素绑定点击事件
    array[j].onclick = function(){
    var color = '';
    //使用随机数实现背景颜色(16进制)的更换
    for(var i = 0;i < 6;i++){
        var num = Math.round(Math.random() * 15);
        if(num == 10){
            num = 'a';
        }else if(num == 11){
            num = 'b';
        }else if(num == 12){
            num = 'c';
        }else if(num == 13){
            num = 'd';
        }else if(num == 14){
            num = 'e';
        }else if(num == 15){
            num = 'f';
        }
        color = color + num;
    }
    //修改元素背景样式
    //this表示当前触发事件的元素
    this.style.backgroundColor = "#" + color;
}
}

dom.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- defer表示延迟加载;但只能用在外部引入的方式中 -->
    <script src="./js/dom.js" defer></script>
</head>
<body>
    <div id="aa">hello1</div>
    <div class="bb">hello2</div>
    <div class="bb">hello3</div>
</body>
</html>

解析:因为HTML中有两个类名为“bb”的div标签,所以js文件中array数组获取的元素有两个,结果如下:

 

如果在点击方法中使用console.log(array[j])打印点击的属性,你会发现结果是undefined,打印j的值发现j=2,而数组array的长度是2,最大索引为1,所以会出现undefined结果。

那j=2,为什么array[j].onclick绑定事件就可以呢?

因为onclick点击事件只有点击时才调用,循环是在点击之前就已经完成了,所以循环结束时j的值为2,而点击事件没有调用。

array[j].onclick=function()在循环中就相当于定义了两次,array[0].onclick=function()和array[1].onclick=function(),所以可以为数组中每个元素绑定事件。

如何实现点击哪个元素就能获取到哪个元素呢?

这就得使用this关键字了,this在这里就表示点击谁,就表示谁,即表示调用者(array[0].onclick=function()中就是array[0]调用的onclick方法,array[0]是调用者)。从而this.style.backgroundColor = "#" + color 相当于 array[0].style.backgroundColor = "#" + color;为指定元素设置样式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值