Javascript中的闭包继承
我正在尝试学习Javascript继承,我已经阅读了一些参考资料Javascript中的闭包继承,javascript,oop,inheritance,closures,Javascript,Oop,Inheritance,Closures,我正在尝试学习Javascript继承,我已经阅读了一些参考资料 关于在Javascript中继承对象以开始的堆栈溢出 我的目标是从外部隐藏私有成员,我认为继承和创建对象的闭包方式可能会对我有所帮助,即使它对内存不是很友好,因此我提出了以下代码: "use strict"; //State is 'saved' by the closure capturing the value var Contact = function(address) { this.setAddressTo
"use strict";
//State is 'saved' by the closure capturing the value
var Contact = function(address)
{
this.setAddressTo = function(newAddress)
{
address = newAddress;
};
this.getAddress = function()
{
return address;
}
};
var Person = function(name, surname, address)
{
//Superclass 'constructor' which will inherit everything public
Contact.call(this, address);
//Subclass members
this.getName = function()
{
return name;
};
this.setName = function(newName)
{
name = newName;
};
this.getSurname = function()
{
return surname;
};
this.setName = function(newSurname)
{
surname = newSurname;
};
//Also with the prototype chaining I can access superclass methods
this.setAddressTo = function(newAddress)
{
console.log('Setting address from base class');
Person.prototype.setAddressTo(newAddress);
}
}
Person.prototype = Object.create(Contact.prototype);
var p1 = new Person('#1.Name', '#1.Surname', '#1.Address');
var p2 = new Person('#2.Name', '#2.Surname', '#2.Address');
console.log('P1 is a person ? ' + (p1 instanceof Person)); //Yes
console.log('P1 is a contact ? ' + (p1 instanceof Contact)); //Yes
console.log('P2 is a person ? ' + (p2 instanceof Person)); //Yes
console.log('P2 is a contact ? ' + (p2 instanceof Contact)); //Yes
console.log(p1.getAddress()); //'#1.Address'
console.log(p2.getAddress()); //'#1.Address'
p1.setAddressTo('#1.Other_Address');
p2.setAddressTo('#2.Other_Address');
console.log(p1.getAddress()); //'#1.Other_Address'
console.log(p2.getAddress()); //'#2.Other_Address'
//Should be undefined because it is not accesible
console.log(p1.address);
console.log(p2.address);
该行:
Person.prototype = Object.create(Contact.prototype);
我使用它使“instanceof”操作符正常工作(这意味着Person对象是Person和Contact的实例)
这样做对吗
这些线路:
var p1 = new Person('#1.Name', '#1.Surname', '#1.Address');
var p2 = new Person('#2.Name', '#2.Surname', '#2.Address');
使用“new”调用函数Person()是否正确
对我来说,这是有意义的,因为我将收到一个新对象,其原型设置为Person.prototype,其原型设置为Contact.prototype(我猜),这将使新创建的对象实际上成为一个人
我所发布的方法对于在Javascript中正确实现继承是有效的,或者存在其他更好的最佳实践来实现相同的目标?如果您不调用
新人(…)
p1将是未定义的,并且在调用p1.getAddress()
时将出现TypeError
,除非您添加并返回此值
在Person函数的末尾是的,你是对的。我应该说得更具体一些,并且应该补充一点,要使用不带“new”运算符的函数,它应该有一个“return”语句。是的,您已经实现了继承。是的,使用newperson()
是正确的。是的,地址
属性的存储在闭包中是私有的。除此之外,我真的不知道你在问什么。这听起来像是对工作代码的代码审查请求。你的问题还有别的吗?仅供参考,这里有一个关于私有成员变量的古老教程:。基本上,问题是在Javascript中是否可以认为它是正确的,或者是否有不同的更好的实践来实现相同的结果。无论如何,感谢您的回复。尽管没有动态分配,p1将不会启动。