【发布时间】:2014-07-10 14:03:59
【问题描述】:
如果这个问题太模糊,请告诉我,我会记下来或尝试添加更多代码示例,谢谢!
这篇文章的灵感来自Yehuta Katz' article on "Understanding Prototypes"
在 Javascript 中,您可以通过使用 Object.create() 来利用原型,这将产生类似于许多 OOP 语言中的依赖/继承。如果null 的参数传递给create() 方法,那么这个新对象将是顶级对象,与Object.prototype 处于同一级别。
现在,也许这只是我使用 Java 和 C# 的几年,但是什么时候会创建一个顶级对象呢?如果您对Object.prototype 中的字段/方法不满意,为什么不直接扩展它并制作您自己的伪顶级对象?
示例:
在这个例子中,person 是一个顶级对象。因此,它没有继承Object.prototype中包含的标准方法,例如toString()、hasOwnProperty()、valueOf()等。
var person = Object.create(null);
// instead of using defineProperty and specifying writable,
// configurable, and enumerable, we can just assign the
// value directly and JavaScript will take care of the rest
person['fullName'] = function() {
return this.firstName + ' ' + this.lastName;
};
// this time, let's make man's prototype person, so all
// men share the fullName function
var man = Object.create(person);
man['sex'] = "male";
var yehuda = Object.create(man);
yehuda['firstName'] = "Yehuda";
yehuda['lastName'] = "Katz";
yehuda.sex // "male"
yehuda.fullName() // "Yehuda Katz"
【问题讨论】:
-
一般?当你想避免意外时——(例如使用地图对象)——你希望在真实对象中出现这种情况的实际情况非常罕见。
标签: javascript inheritance prototype