gpt4 book ai didi

Javascript 原型(prototype)和访问类的问题

转载 作者:数据小太阳 更新时间:2023-10-29 04:32:53 25 4
gpt4 key购买 nike

Family = function(name) {
this._Name = name;
}

Family.prototype = {
getName: function() {
return this._Name;
},
People: function(num) {
this._Number = num;
}
}

Family.People.prototype = {
clearNumber: function() {
this._Number = 0;
}
}

People 是一个嵌套类。它的父类是 Family。

我得到的错误是 Family.People 未定义。有人可以更正上面的代码吗?

最佳答案

工作代码

// function doesn't need "new" operator
var Family = function(name) { this._Name = name; };

Family.prototype = {
getName: function() { return this._Name; }, // missing comma
People: function(num) {
this._Number = num;
}
};

// work with prototypes
Family.prototype.People.prototype = {
clearNumber: function() { this._Number = 0; }
};

这会起作用。但是你必须知道,当你打电话时:

var f = new Family("Doe");

f.People 只是一个对象构造函数,而不是某个其他对象的实例。您还必须实例化它:

f.members = new f.People(3);

你的实例中有一个构造函数,这很令人困惑。

更好的方法

因此,如果您以这种方式编写原型(prototype)可能会更好:

var Family = function(name) {
this._Name = name;
this.getName = function() { return this._Name; };
};

Family.People = function(num) {
this._Number = num;
this.clearNumber = function() { this._Number = 0; };
};

这实际上是在一个类中创建一个类(而不是在实例中)。所以上面的行会这样称呼:

var f = new Family("Doe");
f.members = new Family.People(3);

f 实例的向下钻取如下所示:

f
_Name
getName()
members
_Number
clearNumber()

私有(private)变量

var Family = function(name) {
var _name = name;
this.getName = function() { return _name; };
};

Family.People = function(num) {
var _num = num;
this.getNumber = function() { return _num; }
this.clearNumber = function() { _num = 0; };
};

通过这种方式,我们将变量设为私有(private)并且只能在内部访问,因此无法在外部对其进行操作。您必须始终使用函数来操作它们。这使得它更加健壮,尤其是当存在与变量值相关的某些业务规则时。

var f = new Family("Doe");
f._name; // this is undefined because "_name" is private closure variable

向下钻取 f 实例现在看起来更像是一个类对象实例:

f
getName()
members
getNumber()
clearNumber()

关于Javascript 原型(prototype)和访问类的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5999928/

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