2016-04-27 3 views
1

im пытается сделать 2 объекта из моих 2 классов, объекта Person и объекта Drink, затем я хочу позвонить в мой , выпивая метод передачи объекта Drinkbut i dont know how, how Я могу это сделать? Вот мой код, я не могу понять, почему он не работаетjavascript, используя метод объекта в другом объекте

function Drink(full, alcoholic){ 
    this.alcoholic = alcoholic; 
    this.full = full; 
} 

function Person(name, age) { 
    this.name = name; 
    this.age = age; 
    this.drinking = function drinking(Drink) { 
     if (age >= 18) { 
      this.Drink.full = false; 
     } else { 
      console.log("you cannot drink because of your age") 
      this.Drink.full=true; 
     }; 
    } 
} 

John = new Person("John",24); 
Sam = new Person("Sam",2); 
x = new Drink(true,true); 

console.log(x) 
console.log(John.drinking(x)) 
console.log(Sam.drinking(x)) 
+1

Что именно не работает? Что вы ожидаете? –

+0

Это просто «напиток», если вы хотите обратиться к параметру, а не 'this.Drink' – Bergi

ответ

1

Удалить это на this.Drink

function Drink(full,alcoholic){ 
    this.alcoholic = alcoholic; 
    this.full = full; 
} 

function Person(name,age){ 
    this.name = name; 
    this.age = age; 
    this.drinking= function drinking(drink) { 
    if (age>=18) { 
     drink.full=false;  
    } else { 
     console.log("no puede tomar") 
     drink.full=true; 
    }; 
    } 
} 

John = new Person("John",24); 
Sam = new Person("Sam",2); 
x = new Drink(true,true); 

console.log(x) 
console.log(John.drinking(x)) 
console.log(Sam.drinking(x)) 
+0

Еще лучше, используйте' drink' вместо этого, чтобы не было никаких коллизий имен ... –

+0

Да, Майк, вы правильно. Отредактировано :) – fdfey

+0

Напротив, вы также можете использовать 'this.age' вместо' age'. – Bergi