我创建了一个 person 构造函数,并采用了 firstname = fn
、lastname = ln
和 dateofbirth = dob
。
该代码是:
function Person(fn, ln, dob){
this.fn = fn;
this.ln = ln;
this.dob = new Date(dob);
}
我还添加了原型(prototype)
Person.prototype.calcAge = function(){
const diff = Date.now() - this.dob.getTime();
const age = new Date(diff);
return Math.abs(age.getUTCFullYear() - 1970);
}
这是我的第一个 Person 构造函数。
第二个构造函数我被视为客户构造函数,代码是:
function Customer(fn,ln,phone,membership){
Person.call(this,fn,ln);
this.phone = phone;
this.membership = membership;
}
我正在从人到客户继承原型(prototype)
//Inheriting Person Prototype
Customer.prototype = Object.create(Person.prototype);
// Making Customer Prototype
Customer.prototype.constructor = Customer;
我正在控制台日志记录:
const Customer1 = new Customer('Sairam', 'Gudiputis', '790-139-7848', 'Premium');
console.log(Customer1)
但是在控制台中我得到了无效的出生日期,我没有在客户中使用..
function Person(fn, ln, dob){
this.fn = fn;
this.ln = ln;
this.dob = new Date(dob);
}
Person.prototype.calcAge = function(){
const diff = Date.now() - this.dob.getTime();
const age = new Date(diff);
return Math.abs(age.getUTCFullYear() - 1970);
}
function Customer(fn,ln,phone,membership){
Person.call(this,fn,ln);
this.phone = phone;
this.membership = membership;
}
//Inheriting Person Prototype
Customer.prototype = Object.create(Person.prototype);
// Making Customer Prototype
Customer.prototype.constructor = Customer;
const Customer1 = new Customer('Sairam', 'Gudiputis', '790-139-7848', 'Premium');
console.log(Customer1)
最佳答案
如果您不希望 Customer
中包含 dob
,请添加:
if (!(this instanceof Customer)) {
this.dob = new Date(dob);
}
在 Person
构造函数中:
function Person(fn, ln, dob){
this.fn = fn;
this.ln = ln;
if (!(this instanceof Customer)) {
this.dob = new Date(dob);
}
}
Person.prototype.calcAge = function(){
const diff = Date.now() - this.dob.getTime();
const age = new Date(diff);
return Math.abs(age.getUTCFullYear() - 1970);
}
function Customer(fn,ln,phone,membership){
Person.call(this,fn,ln);
this.phone = phone;
this.membership = membership;
}
//Inheriting Person Prototype
Customer.prototype = Object.create(Person.prototype);
// Making Customer Prototype
Customer.prototype.constructor = Customer;
const Customer1 = new Customer('Sairam', 'Gudiputis', '790-139-7848', 'Premium');
console.log(Customer1)
关于javascript - 原型(prototype)继承是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58506671/