Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript原型属性_Javascript_Prototype - Fatal编程技术网

Javascript原型属性

Javascript原型属性,javascript,prototype,Javascript,Prototype,有一点我很困惑 他们定义了一个Person类,如下所示: 属性应该在类的prototype属性中设置 (函数)以便继承正确工作 后来,当他们给出一个继承的例子时,他们删除了gender属性(为了清楚起见,我假设),所以我不确定行Person.prototype.gender=''首先会执行 我试过这个: function Person(gender) { this.gender = gender; } Person.prototype.gender = 'default'; functi

有一点我很困惑

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

属性应该在类的prototype属性中设置 (函数)以便继承正确工作

后来,当他们给出一个继承的例子时,他们删除了
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

如果要从原型继承对象的值,则不能直接在对象上设置属性

function Person(gender) {
  if (typeof gender !== 'undefined') this.gender = gender;
}
另外,当唯一的目标是设置原型链时,避免更新对象。在某些情况下,像下面这样使用
new
可能会产生不良副作用

Student.prototype = new Person();
应替换为:

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

它不会做任何事情,因为您正在对象本身上设置具有相同名称的属性,这会在原型上隐藏该属性。但是有些工具可能需要这样做,这也可能会使“类”的接口更清晰。如果您想知道JavaScript如何使用原型查找属性以及阴影是什么,那么您可以阅读以下答案:它提供了更多细节和一些示例。还有一些问题可以通过使用Object.create来解决,以及如何传递构造函数参数(或者通常将参数传递给一系列函数)。提醒您,
Object.create()
需要IE9+。并不是每个人都放弃了支持IE8(很多人放弃了,但不是全部),而且大多数时候
newX()
没有副作用。
Student.prototype = Object.create(Person.prototype);