Web开发编程网
分享Web开发相关技术

JavaScript继承并理解原型链

Javascript有一个有趣的继承模型,它与大多数OOP语言完全不同。虽然它是面向对象的,但对象没有从其获取方法的类。相反,它已具雏形, 这被称为基于原型的继承(与对比基于类的继承 ,以了解这两者之间的区别,因为它们是不等价的,并导致许多混乱的路线是很重要的。 尽管JavaScript有自推出关键字支持OOP,这是其基于原型的继承模型只是语法糖-一切都没有从根本上改变。

class

function关键字 定义一个类

让我们来看看一个“类”,使用已定义function关键字:

function Animal(name, energy) {
  // _secret is a private property, which cannot be accessed with a dot-notation
  const _secret = 100;
  // name and energy are public properties, can be accessed with a dot-notation
  this.name = name;
  this.energy = energy;
  // this function is public, and returns the value of the private _secret property (but prevents it from being modified)
  this.getSecret = () => _secret;
}

// all properties under prototype are shared methods across all instances of a function.
Animal.prototype.sleep = function(energyReplenished) {
  console.log(`${this.name} is sleeping.`);
  this.energy += energyReplenished;
};
Animal.prototype.play = function(energyLost) {
  console.log(`${this.name} is playing.`);
  this.energy -= energyLost;
};

注: _secret是私有财产不是因为_它的变量名称的前缀,而是因为我们没有特别把它定义为一个属性this

基于原型的继承

现在,让我们来看看继承:

function Dog(name, energy, breed) {
  // every instance of Dog will now have a name and energy property.
  Animal.call(this, name, energy); // look at the Animal function above - notice how it takes in `name` and `energy` as the two parameters
  // in addition to the properties created by the Animal function, Dog also has its own properties now as well
  this.breed = breed;
}

// Dog has the same prototypes that are definded in Animal,
Dog.prototype = Object.create(Animal.prototype);

// but also some of its own as well:
Dog.prototype.bark = function () {
  console.log('Woof Woof!');
  this.energy -= 0.1;
}

// Let Dog's constructor point to itself, not Animal
Dog.prototype.constructor = Dog;

感谢您的阅读,希望您喜欢!
坍方

未经允许不得转载:WEB开发编程网 » JavaScript继承并理解原型链

WEB开发编程网

谢谢支持,我们一直在努力

安全提示:您正在对WEB开发编程网进行赞赏操作,一但支付,不可返还。