function Person(name, age) {
this.name = name;
this.age = age;
this.run = function() {
console.log(`${this.name}--${this.age}`);
};
}
Person.prototype.sex = "男";
Person.prototype.work = function() {
console.log(`${this.name}的性别是${this.sex}`);
};
// 对象冒充实例继承
// 能继承构造函数中的属性和方法,但是不能继承原型链上的属性和方法
function Web(name, age) {
Person.call(this, name, age);
}
const web = new Web("JonSnow", 21);
console.log(web.name); //JonSnow
console.log(web.sex); //undefined
web.run();
web.work(); //报错
function Person(name, age) {
this.name = name;
this.age = age;
this.run = function() {
console.log(`${this.name}--${this.age}`);
};
}
Person.prototype.sex = "男";
Person.prototype.work = function() {
console.log(`${this.name}的性别是${this.sex}`);
};
function Web(name, age) {}
Web.prototype = new Person();
const web = new Web("JonSnow", 21);
console.log(web.name); //undefined
console.log(web.sex); //男
web.run(); //undefined--undefined
web.work(); //undefined的性别是男
function Person(name, age) {
this.name = name;
this.age = age;
this.run = function() {
console.log(`${this.name}--${this.age}`);
};
}
Person.prototype.sex = "男";
Person.prototype.work = function() {
console.log(`${this.name}的性别是${this.sex}`);
};
function Web(name, age) {
Person.call(this, name, age);
}
Web.prototype = new Person();
const web = new Web("JonSnow", 21);
console.log(web.name); //JonSnow
console.log(web.sex); //男
web.run(); //JonSnow--JonSnow
web.work(); //JonSnow的性别是男
网友评论