我试图了解原型是如何工作的。我有这个例子:
function Person(name) {
if (arguments.length > 0)
this.init(name);
}
Person.prototype.init = function(name) {
this.name = name();
}
Employee.prototype = new Person();
function Employee (name, id) {
if (arguments.length > 0) {
this.init(name);
this.id = id;
}
}
var employee = new Employee("frank",01);
alert(employee.name);//returns frank
我试图弄清楚如何组合前两个部分,并在函数构造函数中分配“init”属性。我有这个,但它不返回任何东西:
function Person(name) {
if (arguments.length > 0)
this.init = function(name) {
this.name = name;
}
}
Employee.prototype = new Person();
function Employee (name, id) {
if (arguments.length > 0) {
this.init(name);
this.id = id;
}
}
var employee = new Employee("frank",01);
alert(employee.name);//returns nothing
我假设我在分配 init 时做错了,但我不知道是什么。将初始属性更改为
this.init(name) = function(name) {
也不行。