gpt4 book ai didi

javascript - 原型(prototype)继承是错误的

转载 作者:行者123 更新时间:2023-11-28 03:27:25 25 4
gpt4 key购买 nike

我创建了一个 person 构造函数,并采用了 firstname = fnlastname = lndateofbirth = 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com