es5继承

2019-11-21  本文已影响0人  Wrestle_Mania
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的性别是男
上一篇下一篇

猜你喜欢

热点阅读