gpt4 book ai didi

javascript - 是否可以在不使用 "new"关键字的情况下使用 Javascript 原型(prototype)?

转载 作者:行者123 更新时间:2023-11-29 10:41:16 27 4
gpt4 key购买 nike

Javascript 使用函数创建对象这一事实起初让我感到困惑。像这样的例子经常被用来强调原型(prototype)是如何在 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');

是否可以在不使用 new FunctionName() 的情况下使用原型(prototype)? IE。像这样:

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 来创建对象。相反,它直接创建对象。

如果没有像 Object.__proto__ 这样的弃用功能或像 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());

或者,您可以使用 new ES 2015's __proto__ property在声明时设置原型(prototype):

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 而不是构造函数内部,除非您需要 私有(private)状态(这样只有一个 实例setModel 方法,而不是类的每个实例一个方法实例):

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

即使使用构造函数,您也可以使用 Object.create 解决 new Car 的奇怪问题:

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

关于javascript - 是否可以在不使用 "new"关键字的情况下使用 Javascript 原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28572553/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com