2016-04-27 84 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

相关问题