Jonvy

导航

Javascript经典问题2

这段程序的输出是什么?

function Dog(name) {
this.name = name;
}

Dog.prototype.bark = function () {
console.log(this.name + " likes barking! Bark!");
};

var max = new Dog("Max", "Buddy");
max.bark();

输出结果

 
Max likes barking! Bark!

为什么?

1. Dog 构造函数

  • Dog 是一个构造函数,用于创建 Dog 对象。

  • 当 new Dog("Max", "Buddy") 执行时:

    • this 指向新创建的 Dog 实例(max)。

    • this.name = name 将 name(即 "Max")赋值给 max.name

    • 第二个参数 "Buddy" 被忽略,因为 Dog 构造函数只接受 name 参数。

2. Dog.prototype.bark

  • bark 方法被添加到 Dog.prototype,所有 Dog 实例都会继承它。

  • 当 max.bark() 调用时:

    • this 指向 max(即 Dog 的实例)。

    • this.name 是 "Max",所以输出 "Max likes barking! Bark!"




posted on 2025-08-05 12:03  不亮  阅读(5)  评论(0)    收藏  举报