// 用户构造函数functionUser(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 =newUser('Alice',30);const user2 =newUser('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 的指向functiongreet(){
console.log(`Hello, ${this.name}`);}const user3 ={ name:'Charlie'};greet.call(user3);// 输出: Hello, Charlie// 修改后的 introduceWithAge 函数,接收多个参数functionintroduceWithAge(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.