JS基础练习|控制this的call、apply、bind

// 用户构造函数
function User(name, age) {
  this.name = name;
  this.age = age;
}

// introduce 方法,使用 this 来访问对象的属性
User.prototype.introduce = function() {
  console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
};

// 创建 User 实例
const user1 = new User('Alice', 30);
const user2 = new User('Bob', 25);

// 直接调用实例的方法
user1.introduce(); // 输出: Hi, I'm Alice and I'm 30 years old.
user2.introduce(); // 输出: Hi, I'm Bob and I'm 25 years old.

// 使用 call 来改变 this 的指向
function greet() {
  console.log(`Hello, ${this.name}`);
}

const user3 = { name: 'Charlie' };
greet.call(user3); // 输出: Hello, Charlie

// 修改后的 introduceWithAge 函数,接收多个参数
function introduceWithAge(age, hobby) {
  console.log(`Hi, I'm ${this.name}, I'm ${age} years old, and I love ${hobby}.`);
}

// 使用 apply 来传递多个参数
introduceWithAge.apply(user1, [30, 'painting']); 
// 输出: Hi, I'm Alice, I'm 30 years old, and I love painting.

// 使用 bind 来创建一个新函数
const introduceBob = user2.introduce.bind(user2);
introduceBob(); // 输出: Hi, I'm Bob and I'm 25 years old.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值