2016-04-27 122 views
1

即時嘗試從我的2類,Person對象和Drink對象,使2個對象,然後我想打電話給我的方法傳遞Drink對象,但我不知道如何,如何我可以那樣做嗎?這裏是我的代碼,我不能明白爲什麼它不工作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

這只是'Drink',如果你想參考的參數,而不是'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

相關問題