Javascript 原型属性阴影
Javascript prototype property shadowed
我对Javascript原型机制有点困惑。我有以下代码:
function Person () {
this.name = "no name";
this.setName = function (n) {
this.name = n;
}
}
function Student () {
this.id = "123";
}
Student.prototype = new Person();
s = new Student();
s.setName("Klaus");
执行代码后,对象 s 有两个名称。对象本身的名称"Klaus"和原型中的"noname"名称。我知道这个物业是阴影的,它工作得很好,但这感觉不自然?!有没有更好的方法只使用原型的属性?
您可以直接处理原型属性,但这需要不成比例的工作量,并且可能不被视为最佳实践。相反,您可以在正确的this
上下文中调用 Person
构造函数。
首先,强烈建议在分配给函数的 prototype
属性时使用 Object.create
而不是 new
运算符。使用 new
运算符时,将调用 Person
构造函数,但在错误的this
上下文中。为了防止这种情况,您可以像这样链接它们:
Student.prototype = Object.create(Person.prototype);
相反,如果要在 Student 中调用原型链接 ( Person
) 的构造函数,则可以在构造函数中使用正确的this
上下文call
它:
function Student () {
Person.call(this);
this.id = "123";
}
另外,除非您想为每个实例创建一个函数,否则我会将setName
函数移动到Person
的[[Prototype]]
:
function Person () {
this.name = "no name";
}
Person.prototype.setName = function (n) {
this.name = n;
}
function Student () {
Person.call(this); // Call the Person constructor
this.id = "123";
}
Student.prototype = Object.create(Person.prototype);
s = new Student();
// s.name is 'no name'
s.setName("Klaus");
// s.name is 'Klaus'
或者,如@Teemu所述,您也可以将 name
属性放在Person.prototype
上以将其用作默认值:
function Person () {
}
Person.prototype.setName = function (n) {
this.name = n;
}
Person.prototype.name = "no name"; // Define the name directly
function Student () {
Person.call(this); // you only need this, if there are other things happening in the Person constructor that you need as well
this.id = "123";
}
Student.prototype = Object.create(Person.prototype);
s = new Student();
// s.name is 'no name'
s.setName("Klaus");
// s.name is 'Klaus'
相关文章:
- RegEx删除空属性?例如,如果(class=“”||class=“”)移除;否则就下课
- 全局变量和全局对象的属性之间有什么区别吗
- 如果使用 lodash 将属性存在于另一个对象中,则向对象添加属性
- 如何在Bootstrap Modal中为动态点击生成的变量设置jade属性
- 序列化数据属性中对象的最可靠方法
- 分析高度属性时出现意外值{{specs.height}}.index.html
- TypeError:无法读取属性'推'未定义的JavaScript
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- AngularJS-使用'true'属性
- 可以't使用JavaScript获取width属性
- 未捕获的TypeError无法读取未定义的属性socialsharing
- 带有填充属性的SVG矩形显示在包含元素的上方插入框阴影
- Javascript设置&阴影属性(原型链)
- 具有不更新阴影的变形属性的动画缓冲区几何图形
- Javascript 原型属性阴影
- 如何使用.style JavaScript属性添加css框阴影
- 使用javascript/jquery访问阴影DOM属性(聚合物)
- 如何在lodash中创建一个带有阴影属性的新对象
- 加载OBJ在Three.js不接收阴影,即使属性设置为true
- 在javascript中使用DOM设置文本阴影属性的值