使用new和不使用new都可以创建JavaScript对象 + 继承

3

我正在使用JavaScript创建一个库,该库创建JavaScript对象。

  1. 如何编写库的接口,以便其用户可以使用WITH和WITHOUT同时创建这些对象?(我看到了很多答案,建议构造函数自动调用自己,如果它们首先没有被调用,则使用new,但是反过来不行)。
  2. 我们可以在Object.create中使用new吗?例如: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.

非常感谢你。

2
如果一个构造函数返回一个对象,new 将没有效果。或许可以深入研究一下。示例 - undefined
这本书的第三章可能会对你有所帮助。 - undefined
那么,例如我可以直接返回Object.Create吗?它能在有或没有使用new的情况下都正常工作(包括继承)吗? - undefined
1个回答

3
我会做以下事情:
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

2
Dog.prototype = Animal.prototype之后,你必须将Dog的构造函数设置为Dog。别忘了加上一些分号。 - undefined
2
我认为你将Animal.prototype.constructor设置为Dog是因为你没有克隆原型。 - undefined
我在想是否有一种方法可以在Animal.prototype上设置name,以便Dog可以继承它。 - undefined
这是无效的代码。Object.create返回的对象永远不是一个构造函数。 - undefined
在调用Object.Create之前,如何检测是否有新的对象产生? - undefined
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接