Javascript 创建具有 new 和不具有 new + 继承的对象

标签 javascript inheritance constructor factory

我正在用 javascript 创建一个库来创建 javascript 对象。

  1. 我如何编写图书馆的界面,以便他们的用户可以 使用和不使用 new 创建这样的对象? (我看到了很多建议的构造函数,如果它们首先没有被 new 调用,那么构造函数会自动用 new 调用自身,反之则不然)。
  2. 我们可以将 new 与 Object.create 一起使用吗?例如: let dog = new Object.create(animal);
  3. 如何提供继承

用代码来说明,你如何编写下面的函数Animal和Dog才能使下面的表达式有效:

let animal = new Animal(); // valid
let animal = Animal(); // valid also, we should return the same object
let dog = new Dog(); // valid, dog inherits/shares functions and properties from Animal.
let dog = Dog(); // valid also, same case as in previous call.

非常感谢。

最佳答案

我会这样做:

function Animal(name) {
  if(!(this instanceof Animal)) {
    return new Animal(name);
  }

  this.name = name;
}

Animal.prototype.walk = function() { console.log(this.name, 'is walking...'); };

function Dog(name) {
  if(!(this instanceof Dog)) {
    return new Dog(name);
  }

  this.name = name;
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

var animal = Animal('John');
var other_animal = new Animal('Bob');

var dog = Dog('Blue');
var other_dog = new Dog('Brutus');

animal.walk(); // John is walking...
other_animal.walk(); // Bob is walking...

dog.walk(); // Blue is walking...
other_dog.walk(); // Brutus is walking...

console.log(dog instanceof Animal); // true
console.log(dog instanceof Dog); // true

关于Javascript 创建具有 new 和不具有 new + 继承的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43545589/

相关文章:

python - 在 python 中调用 int 的 __init__ 看似微不足道的问题

c++ - 多个构造函数的内存使用c++

java - 将多个字符串映射到一个值

java - 当对象调用其父类(super class)的方法时如何处理对象?

java构造函数不能应用于给定类型android studio

javascript - 如何在ES6中引用未命名的解构参数?

javascript - 仅当我有两个 <li> 标签时图像才会更改

javascript - 如何防止 iPhone(包括 iOS 7)在 HTML 或 JS 中进入休眠状态?

javascript - d3.js 作为带有 cordova 的应用程序运行

c# - 从类或抽象类继承