Javascript继承问题
为什么下面代码中的版本 2 不会产生与版本 1 相同的结果?
function person(name) {
this.name = name;
}
function student(id, name) {
this.id = id;
// Version 1
//this.inherit_from_person = person;
//this.inherit_from_person(name);
// Version 2
person(name);
}
s = new student(5, 'Misha');
document.write(s.name); // Version 1 => Misha
// Version 2 => undefined
Why Version 2 in the code below does not produce the same result as Version 1 ?
function person(name) {
this.name = name;
}
function student(id, name) {
this.id = id;
// Version 1
//this.inherit_from_person = person;
//this.inherit_from_person(name);
// Version 2
person(name);
}
s = new student(5, 'Misha');
document.write(s.name); // Version 1 => Misha
// Version 2 => undefined
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您调用
person(name)
时,它会通过绑定到全局对象的this
进行调用,因此只需设置window.name = "Misha"
。您希望person.call(this, name)
将其显式绑定到右侧的this
。When you call
person(name)
it gets called withthis
bound to the global object, so that's just settingwindow.name = "Misha"
. You wantperson.call(this, name)
to explicitly bind it to the rightthis
.在我看来,您正在尝试实现原型继承。下面是一个经典的例子,虽然用得不多。 javascript 中不需要复杂的继承,通常只需要单个实例即可。如果需要多个实例,模块模式可以与共享方法和属性的闭包一起使用,也可以提供私有和特权成员。
请注意,instanceof 运算符不是很可靠,但在上述情况下它可以正常工作。此外,所有方法和属性都是公共的,因此很容易被重写。
It looks to me like you are trying to implement prototype inheritance. Below is a classic example, though not much used. Complex inheritance is just not needed in javascript, usually a single instance is all that is required. If multiple instances are required, the module pattern can be used with closures for shared methods and properties and also to provide private and priveliged members.
Note that the instanceof operator is not very reliable, but it works fine in the above case. Also all methods and properties are public so easily over written.