неправильное наследование прототипа - PullRequest
1 голос
/ 22 октября 2019

Я создал конструктор персонажа, и я беру firstname = fn, lastname = ln и dateofbirth = dob.

Этот код:

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);
}

Это мой первый конструктор Person.

и второй конструктор, я взят в качестве конструктора клиента, и этот код:

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)

, но в консоли я получаю недопустимую дату рождения, которую я не использую в клиенте ..

    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)

1 Ответ

0 голосов
/ 22 октября 2019

Если вы не хотите dob в Customer, добавьте:

      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)
...