是否可以在不使用“new”的情况下使用Javascript原型关键词? [英] Is it possible to using Javascript prototypes without using the "new" keyword?

查看:99
本文介绍了是否可以在不使用“new”的情况下使用Javascript原型关键词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript使用函数创建对象的事实起初让我很困惑。像这样的例子通常用于突出原型如何在Javascript中工作:

The fact that Javascript uses functions to create objects was confusing to me at first. An example like this is often used to highlight how prototypes work in Javascript:

function Car(){
  this.setModel=function(model){
    this.model=model;
  }
  this.getModel=function(){
    return this.model;
  }
}

function Bus(){}
Bus.prototype=new Car();

var obj=new Bus();
obj.setModel('A Bus');
alert(obj.getModel('A Bus');

是否可以使用原型没有使用新的FunctionName()?就像这样:

Is it possible to use prototypes without using new FunctionName()? I.e. something like this:

var Car={
  setModel:function(model){
    this.model=model;
  },
  getModel:function(){
    return this.model
  }
}

var Bus={
  prototype:Car;
};

var obj=Bus;
obj.setModel('A Bus');
alert(obj.getModel());

这不使用函数和 new 来创建对象。而是直接创建对象。

This does not use functions and new to create objects. Rather, it creates objects directly.

这是否可能没有弃用的功能,如 Object .__ proto __ 或实验函数,如 Object.setPrototypeOf()

Is this possible without deprecated features like Object.__proto__ or experimental functions like Object.setPrototypeOf()?

推荐答案

Object.create 获取您正在寻找的行为,但您必须调用它而不是 new

// Using ES6 style methods here
// These translate directly to
// name: function name(params) { /* implementation here */ }
var Car = {
 setModel(model) {
    this.model = model;
  },
  getModel() {
    return this.model
  }
};

var Bus = Object.create(Car);

var obj = Object.create(Bus);
obj.setModel('A Bus');
alert(obj.getModel());

或者,您可以使用新ES 2015的 __ proto __ property 在申报时设置原型:

Alternatively, you can use the new ES 2015's __proto__ property to set the prototype at declaration time:

var Bus = {
  __proto__: Car
};

// You still need Object.create here since Bus is not a constructor
var obj = Object.create(Bus);
obj.setModel('A Bus');
alert(obj.getModel());



一些额外的笔记



你应该添加 Car.prototype 的方法不在构造函数内部,除非你需要私有状态(这样只有一个<$ c的实例) $ c> setModel 方法,而不是每个类实例的方法的一个实例):

Some additional notes

You should add the methods to Car.prototype not inside of the constructor unless you need the private state (this way there is only one instance of the setModel method, rather than one instance of the method per instance of the class):

function Car() {}
Car.prototype.setModel = function(model) { this.model = model; };
Car.prototype.getModel = function(model) { return this.model; };

你可以绕过新车奇怪使用 Object.create 即使使用构造函数:

You can get around the new Car oddness with Object.create even with constructor functions:

function Bus {}
Bus.prototype = Object.create(Car);

这篇关于是否可以在不使用“new”的情况下使用Javascript原型关键词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆