[英]How to access methods through from another class and create object
OOP Javascript 新手! 我有 2 个类,订单和客户。 我有一个方法 getName()。 我希望 customer 作为我在 Order 类中的属性之一。 我已经为两者创建了对象,但似乎无法访问订单对象中的客户名称。
客户.js
class Customer{
constructor(id, name, address,creditCard) {
this._id=id;
this._name=name;
this._address=address;
this._creditCard=creditCard;
}
getName(){
return this._name;
}
}
订单.js
class Order {
customer;
constructor(id, date) {
this._id = id;
this._date=date;
this.customer=new Customer();
}
getNameCustomer() {
return this.customer.getName();
}
}
数据.js
const customer1 = new Customer(123,"John","123 E Cookie St",'xxxx xxxx xxxx 1223');
const order1= new Order(801,'January 12, 2021 01:15:00',customer1.getNameCustomer() );
let orders=[order1];
您正在调用不存在的customer1
上的getNameCustomer
方法。 你应该使用
customer1.getName()
但是,如果您在Order
类中传递customer
对象并将其设为属性,则可以做得更好:
class Customer { constructor(id, name, address, creditCard) { this._id = id; this._name = name; this._address = address; this._creditCard = creditCard; } getName() { return this._name; } } class Order { constructor(id, date, customer) { this._id = id; this._date = date; this._customer = customer; } getNameCustomer() { return this._customer.getName(); } } const customer1 = new Customer(123, "John", "123 E Cookie St", "xxxx xxxx xxxx 1223"); const order1 = new Order(801, "January 12, 2021 01:15:00", customer1); console.log(order1); console.log(order1.getNameCustomer());
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */ .as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.