Javascript 原型(prototype)属性

标签 javascript prototype

Introduction to Object-Oriented JavaScript一度让我感到困惑。

他们定义了一个 Person 类,如下所示:

Properties should be set in the prototype property of the class (function) so that inheritance works correctly.

function Person(gender) {
  this.gender = gender;
  alert('Person instantiated');
}

Person.prototype.gender = '';

稍后当他们给出继承示例时,他们删除了 gender 属性(为了清楚起见,我假设),所以我不确定 Person.prototype.gender = '' 这行是什么; 放在首位。

我试过这个:

function Person(gender) {
  this.gender = gender;
}

Person.prototype.gender = 'default';

function Student(gender) {
  Person.call(this, gender);
};

Student.prototype = new Person();
Student.prototype.constructor = Student;


var a = new Student('male');
var b = new Student();

console.log(a.gender); //prints 'male'
console.log(b.gender); //I expect 'default', but get undefined

最佳答案

如果你想从原型(prototype)继承它的值,你不能直接在对象上设置属性。

function Person(gender) {
  if (typeof gender !== 'undefined') this.gender = gender;
}

此外,当唯一目标是设置原型(prototype)链时,请避免更新对象。在某些情况下,像下面这样使用 new 可能会产生不良副作用。

Student.prototype = new Person();

应替换为:

Student.prototype = Object.create(Person.prototype);

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

相关文章:

javascript - 在 _.map() 中使用异步函数

javascript - 对象内对象的原型(prototype)

javascript - 空字符串的长度怎么可能大于 0?

javascript - 使用 jquery mobile 每 X 秒动态创建表松开 css 设置

javascript - 阻止/推迟 html 元素的加载

javascript - jQuery 将事件处理程序连接到被触发的对象的方法

javascript - javascript中从一个实例继承

javascript - 为什么我不能在 Javascript 中调用原型(prototype)方法?

javascript - 你如何扩展像 Object 或 Number 这样的内置函数的构造函数?

javascript - 我怎么知道什么时候在 JS 函数上使用 .bind()?