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!"。
-
浙公网安备 33010602011771号