[英]Classical Inheritance in JavaScript : Reassigning the constructor
I am trying to learn inheritance in JavaScript using prototype keyword. 我正在尝试使用原型关键字在JavaScript中学习继承。
I came a code across a web-site which explained me classical inheritance in JavaScript. 我在一个网站上看到了一段代码,向我解释了JavaScript中的经典继承。 I am using Mozilla Rhino for command-line javaScript 我将Mozilla Rhino用于命令行javaScript
This is my code 这是我的代码
var fn55 = function(){
var Employee = function(name){
var name = name;
this.getName = function(){
return name;
};
this.setName = function(empName){
name = empName;
};
};
var ContractEmp = function(name,sal){
var salary = sal;
this.getSalary = function(){
return salary;
}
//calling super constructor
Employee.apply(this,[name]);
};
ContractEmp.prototype = new Employee();
ContractEmp.prototype.constructor = ContractEmp;
var emp1 = new ContractEmp("Jack",3000);
var emp2 = new ContractEmp("John",4000);
print(emp1.getName());
print(emp2.getName());
print(emp1.getName());
Employee.prototype.getInfo = function(){
return "Emp Name \""+this.getName()+"\" Salary "+this.getSalary();
}
print(emp1.getInfo());
};
fn55();
the output is 输出是
Jack
John
Jack
Emp Name "Jack" Salary 3000
Now if I comment a line in my code 现在,如果我在代码中注释一行
//ContractEmp.prototype.constructor = ContractEmp;
the output remains as it is. 输出保持原样。
So my question is, whats the purpose of this re-assigning the constructor 所以我的问题是,重新分配构造函数的目的是什么
So my question is, whats the purpose of this re-assigning the constructor 所以我的问题是,重新分配构造函数的目的是什么
The only purpose is to reset constructor
to its original value. 唯一的目的是将constructor
重置为其原始值。
See also What it the significance of the Javascript constructor property? 另请参见Javascript构造函数属性的意义是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.