[英]How to access methods through from another class and create object
New to OOP Javascript! OOP Javascript 新手! I have 2 classes, Order and Customer.
我有 2 个类,订单和客户。 I have a method getName().
我有一个方法 getName()。 I want customer as one of my properties in the Order class.
我希望 customer 作为我在 Order 类中的属性之一。 I have created objects for both but can't seem to access the customer name in the order object.
我已经为两者创建了对象,但似乎无法访问订单对象中的客户名称。
Customer.js客户.js
class Customer{
constructor(id, name, address,creditCard) {
this._id=id;
this._name=name;
this._address=address;
this._creditCard=creditCard;
}
getName(){
return this._name;
}
}
Order.js订单.js
class Order {
customer;
constructor(id, date) {
this._id = id;
this._date=date;
this.customer=new Customer();
}
getNameCustomer() {
return this.customer.getName();
}
}
data.js数据.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];
You are calling getNameCustomer
method on customer1
which doesn't exist.您正在调用不存在的
customer1
上的getNameCustomer
方法。 You should use你应该使用
customer1.getName()
But you can do better if you pass the customer
object in the Order
class and make it a property as:但是,如果您在
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.