javascript:如何重写某个类的所有实例的方法?
function Person(){
this.scream = function(){
alert('NO NO NO!!!!');
};
}
var steve = new Person();
steve.scream() // NO NO NO!!!!
Person.prototype.scream = function(){
alert('YES YES YES!!!!');
}
steve.scream() // still NO NO NO!!!!
有没有办法在不明确引用 steve 的情况下覆盖“尖叫”?考虑一下当您有多个 Person 实例时的情况。
function Person(){
this.scream = function(){
alert('NO NO NO!!!!');
};
}
var steve = new Person();
steve.scream() // NO NO NO!!!!
Person.prototype.scream = function(){
alert('YES YES YES!!!!');
}
steve.scream() // still NO NO NO!!!!
Is there a way to override 'scream' without referencing steve explicitly? Think about the cases when you have may instances of Person.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,
有了
Person
声明,每次您创建它的新“实例”时,“构造函数”都会运行,并且您将创建一个全新的scream
函数(闭包) ),除了新创建的对象 steve.scream 之外,您没有任何引用。作为替代方案,您可以这样做:
在这种情况下,初始的“方法”仅在原型上的一个位置可用,并且您可以为所有“实例”覆盖它。
No,
Having that
Person
declaration, every time you create a new "instance" of it the "constructor" will run and you'll create a completely newscream
function (closure) which you don't have any reference to, except from the newly created object,steve.scream
that is.As an alternative you may do it like this:
In which case the initial
scream
"method" is available only in one place, on the prototype, and you can overwrite it for all "instances".并且,如果您想继续使用您的代码风格,您可能会喜欢
and, if you want to continue to use your code style, you may like