<script>
//一,实例对象中的属性和原型对象中的属性相同的问题
function Person(name, age,sex) {
this.name= name;
this.age= age;
this.sex = sex;
}
/**JS是一门动态的语言,只要使用了对象点,就产生了属性,如果没有赋值就会为null*/
Person.prototype.sex = "女";
let per = new Person("lily", 25, "男");
console.log(per.name);
console.log(per.age);
console.log(per.sex);
/**
* 实例对象访问属性,首先是从实例对象中找,找到了就直接用,找不到就通过原型对象来找。
*1, 通过实例对象是不能改变原型对象中的属性中
* 2,想要改变原型对象中的值,就通过原型对象.属性来改变
*/
console.log("--------------------------------------------");
//二,继承
function People(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
People.prototype.eat = function () {
console.log("人吃东西")
};
People.prototype.sleep = function () {
console.log("人在睡觉")
};
People.prototype.play = function () {
console.log("人在玩")
};
function Student(score) {
console.log("小明得了"+score+"分.....")
}
Student.prototype = new People("丽丽", 26, "女");
Student.prototype.study=function () {
console.log("学习很累很累的哦.");
};
Student.prototype.playgame = function () {
console.log("小明喜欢玩游戏")
};
let stu = new Student(29);
console.log(stu.sex);
console.log(stu.name);
console.log(stu.age);
stu.study();
stu.play();
stu.sleep();
stu.eat();
// 继承案例
function Animal(name, weight) {
this.name = name;
this.weight = weight;
}
Animal.prototype.eat = function () {
console.log("天天吃东西,就是吃")
};
function Dog(color) {
this.color = color;
}
Dog.prototype = new Animal("哮天犬", "50kg");
Dog.prototype.bitePerson = function () {
console.log("哼 往往咬死你")
};
//哈士奇
function ErHa(sex) {
this.sex = sex;
}
ErHa.prototype = new Dog("黑白色");
ErHa.prototype.playHost = function () {
console.log("能陪主人玩的很开心")
};
let erha = new ErHa("男");
console.log(erha.name,erha.weight,erha.color);
erha.playHost();
//三 以上的这种继承是不能继承原型属性的,所以这里需要采用组合继承来实现相关的功能
function Father(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
Father.prototype.smoke = function () {
console.log("长辈喜欢抽烟")
};
function Son(name, age, sex, study) {
Father.call(this.name,age,sex);
this.study = study;
}
Son.prototype = new Father();//这里不用写
Son.prototype.eat = function () {
console.log("吃东西")
};
let st = new Son("lili" , "男" ,25 , "学习");
st.eat();
st.smoke();
</script>
实例对象和原型对象 继承 组合继承
最新推荐文章于 2024-01-05 00:51:53 发布