Javascript 具有新关键字的函数原型继承
我确信我正确理解了JavaScript的Javascript 具有新关键字的函数原型继承,javascript,prototype,new-operator,Javascript,Prototype,New Operator,我确信我正确理解了JavaScript的new和prototype关键字,但我编写的一些简单代码并没有像我预期的那样运行 var ClassA = function() { return { shout: function() { alert("I can shout"); } }; }; ClassA.prototype.shoutLouder = function() { alert("I CAN SHOUT
new
和prototype
关键字,但我编写的一些简单代码并没有像我预期的那样运行
var ClassA = function() {
return {
shout: function() {
alert("I can shout");
}
};
};
ClassA.prototype.shoutLouder = function() {
alert("I CAN SHOUT");
};
var instance = new ClassA();
instance.shout();
// why not available?
instance.shoutLouder();
当实例变量尝试调用shoutLouder
时,它失败,出现“uncaughttypeerror:instance.shoutLouder不是函数”
但是,在中,它表示在使用new
创建对象时:
将创建一个从Foo.prototype继承的新对象
我的理解错在哪里
对于上面的代码snipbit。
ClassA
返回一个新的、不同的对象
return {
shout: function() {
alert("I can shout");
}
};
试一试
ClassA
返回一个新的、不同的对象
return {
shout: function() {
alert("I can shout");
}
};
试一试
您正在失去对函数(类)原型对象的访问权限,因为您正在从函数中返回一个新对象:
var ClassA = function() {
return {
shout: function() {
alert("I can shout");
}
};
};
鉴于你应该做:
var ClassA = function() {
this.shout = function() {
alert("I can shout");
};
};
这仍然允许您访问prototype对象(因此委派链仍然有效),因为new关键字将从类中返回“This”。您将失去对函数(类)prototype对象的访问权,因为您将从函数中返回一个新对象:
var ClassA = function() {
return {
shout: function() {
alert("I can shout");
}
};
};
鉴于你应该做:
var ClassA = function() {
this.shout = function() {
alert("I can shout");
};
};
这仍然允许您访问prototype对象(因此委托链仍然有效),因为new关键字将从类返回“This”