Javascript原型和访问类的问题

前端之家收集整理的这篇文章主要介绍了Javascript原型和访问类的问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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;
  }
}

人是一个嵌套的类.它的父类是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);

你在你的实例中有一个相当混乱的构造函数.

更好的方法

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

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()

私有变量

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; };
};

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

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

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

f
  getName()
  members
    getNumber()
    clearNumber()
原文链接:https://www.f2er.com/js/157658.html

猜你在找的JavaScript相关文章