Javascript 面向对象的方法声明问题?
一个类
function people(n,a)
{
this.name=n;
this.age=a;
this.car=new Object(); //《---ps:这里声明,是不是和闭包问题有关系?
}
people.prototype.getName=function(){return this.name;}
=====================以上都好理解,现在我要声明对象car的属性和方法,car是people买的一辆汽车,有几个属性
function people(n,a)
{
this.name=n;
this.age=a;
}
people.prototype.getName=function(){return this.name;}
people.car=new Object();// <--ps:把它声明在类外边,是不是合理?
people.car.color= 'red ';// car的属性
people.car.brand= 'BMW ';
people.car.prototype.getColor=function(){return people.car.color;}//ps:与下边的方法不同之处?
people.car.getBrand=function(){return people.car.brand;}
==========上边的属性与方法声明的结构是否正确?
我new 一个people后,people.prototype.getName方法是每个对象共享的,那么car对象呢?是每个people共享还是一个单例,感觉是个单例,因为直接挂在类上了。如果需要每个people都有自己的car对象该怎么声明,最后car对象的两个方法如果都能正常运行的话,是不是就是类方法与对象方法的差别?
有没有造诣深厚的Js高人指点下?
------解决方案-------------------- <script>
function people(n,a)
{
this.name=n;
this.age=a;
this.car=new Object();// <--ps:把它声明在类外边,是不是合理?
this.car.color;
this.car.brand;
this.car.getColor=function(){return this.color;}
this.car.getBrand=function(){return this.brand;}
}
people.prototype.getName=function(){return this.name;}
var Mike = new people( "Mike ", 28);
Mike.car.color = "blue ";
Mike.car.brand = "BMW ";
alert(Mike.getName() + " has a " + Mike.car.getColor() + " " + Mike.car.getBrand());
var Jack = new people( "Jack ", 24);
Jack.car.color = "black ";
Jack.car.brand = "BENZ ";
alert(Jack.getName() + " has a " + Jack.car.getColor() + " " + Jack.car.getBrand());
</script>
------解决方案-------------------- <script type= "text/javascript ">
<!--
function People(){
this.name = " ";
this.car = null;
}
People.prototype.getName = function(){
return this.name;
}
People.prototype.setName = function(name){
this.name = name;
}
People.prototype.buyCar = function(car){
this.car = car;
}
People.prototype.getCar = function(){
return this.car;
}
People.prototype.showCar = function(){
document.write(this.getName(), "的车的颜色是: ",this.getCar().getColor(), " <br> ");
}
function Car(clr){
this.color = clr;
}
Car.prototype.getColor = function(){
return this.color;
}
var p1 = new People();
p1.setName( "刘翔 ");
var p2 = new People();
p2.setName( "姚明 ");
var car1 = new Car( "红色 ");
var car2 = new Car( "黑色 ");
p1.buyCar(car1);
p2.buyCar(car2);
p1.showCar();
p2.showCar();
//-->
</script>
------解决方案-------------------- <script language= "javascript ">
<!--
function people(n,a){
this.name=n;
this.age=a;
this.car=new Object(); //《---ps:这里声明,是不是和闭包问题有关系?
//不是闭包
}
peopl