gpt4 book ai didi

javascript - Javascript中的多级继承

转载 作者:行者123 更新时间:2023-12-04 17:00:23 28 4
gpt4 key购买 nike

我正在尝试使用原型(prototype)在 Javascript 中模拟继承。

我有一个名为 Model 的函数和一种 model => Item。

var Model = function() { 
this.names = ["name1", "name2"];
}
Model.prototype.Item = function(args) {
this.init = function(item_name) {
this.names[0] = item_name; // ERROR: Cannot set property '0' of undefined
}
}
var m = new Model();
var i = new m.Item();
i.init("New Name"); // ERROR: Cannot set property '0' of undefined

如何访问 names来自 init() 的数组上面的功能?

最佳答案

Javascript中的继承很棘手!阅读这篇文章,了解 Javascript 中传统的面向对象继承:http://blog.slaks.net/2013-09-03/traditional-inheritance-in-javascript/ .

var Model = function () {
this.names = ["name1", "name2"];
};

var Item = function () {
//When inheriting in Javascript you must
//call the inherited function's constructor manually.
Model.call(this);
};

//Inherit Model's prototype so you get all of Model's methods.
Item.prototype = Object.create(Model.prototype);
Item.prototype.constructor = Item;

Item.prototype.init = function (item_name) {
this.names[0] = item_name;
};

var Employee = function () {
Model.call(this);
};

Employee.prototype = Object.create(Model.prototype);
Employee.prototype.constructor = Employee;

var myItem = new Item();
myItem.init("New Name");
//prints New Name, name2
console.log(myItem.names);


var myEmployee = new Employee();
//prints name1, name2
console.log(myEmployee.names);

更传统的面向对象语言 (C#) 中的类似代码:
public class Model
{
public Model()
{
this.Names = new[] {"name1", "name2"};
}
public string[] Names { get; set; }
}

public class Item : Model
{
public Item() : base() { }

public void init(string item_name)
{
this.Names[0] = item_name;
}
}

public class Employee : Model
{
public Employee() : base() { }
}

var myItem = new Item();
myItem.init("New Name");
//prints New Name, name2
Console.WriteLine(String.Join(",", myItem.Names));

var myEmployee = new Employee();
//prints name1, name2
Console.WriteLine(String.Join(",", myEmployee.Names));

关于javascript - Javascript中的多级继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24046166/

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