在使用Object时传递参数.创建而不是新建
Passing arguments when using Object.create as opposed to new
这个问题不是Using "Object.create"而不是"new"当使用Object.create
我很好奇如何使用Object.create
而不是new
来初始化对象。下面是我到目前为止的代码:
function Human(eyes) {
this.eyes = eyes || false;
}
Human.prototype.hasEyes = function() {
return this.eyes;
}
function Male(name) {
this.name = name || "No name";
}
Male.prototype = new Human(true); //passing true to the Human constructor
var Sethen = new Male("Sethen");
console.log(Sethen.hasEyes());
正如您在上面看到的,Male.prototype = new Human(true);
用true创建了一个新对象。当hasEyes()
函数运行时,它将按照预期记录为true。
Object.create
我将如何去做同样的方式传递true
参数?? 必须使用Object.call(this)
调用构造函数,然后传递参数。
function Human(eyes, phrase) {
this.eyes = eyes || false;
this.phrase = phrase;
}
Human.prototype.hasEyes = function() {
return this.eyes;
}
Human.prototype.sayPhrase = function() {
return this.phrase;
}
function Male(name) {
Human.call(this, true, "Something to say"); //notice the call and the arguments
this.name = name || "No name";
}
Male.prototype = Object.create(Human.prototype);
var Sethen = new Male("Sethen");
console.log(Sethen.hasEyes());
console.log(Sethen.sayPhrase());
console.log(Object.getOwnPropertyNames(Sethen));
这个工作,现在对象Male
具有eyes
和phrase
的属性
这是否为原型继承模型提供了一些线索?
const Human = {
constructor: function (eyes) {
this.eyes = eyes || false;
},
hasEyes: function () {
return this.eyes;
}
};
let Male = Object.create(Human);
Male.constructor = function (name) {
this.name = name || "No name";
return Human.constructor.call(this, "true");
};
let Sethen = Object.create(Male);
Sethen.constructor = function() {
return Male.constructor.call(this, 'Sethen');
};
Sethen.constructor();
console.log(Sethen.hasEyes());
console.log(Object.getOwnPropertyNames(Sethen));
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 为effect Composer创建GodRays效果过程
- 从javascript创建一个列表
- onkeyup无法动态创建多个文本区域
- 如何使用javascript从主svg对象动态创建svg视图框
- 如何访问声音管理器2创建的声音对象
- 我已经创建了一个jquery转盘,并使用if条件来运行和停止转盘
- Kendo:我该如何在树视图中创建一个递归的hieiarchy
- 使用Facebook live API创建实时视频对象时的隐私设置
- 在动态创建的元素上获取对特定选择器的引用
- 如何创建带有插槽的vue js组件预加载程序
- 如何在创建键时引用来自同一对象的键
- 如何创建JSON数组
- 从html创建一个指令,该指令按类名应用函数
- 使用Javascript创建测验页面
- 在 SharePoint 列表“新建项”页中创建动态查阅列
- 创建分部视图以在索引页中新建
- 我可以让浏览器后退按钮转到编辑页面,而不是在创建时新建
- 创建表,就像新建表一样,单独编号
- 在使用Object时传递参数.创建而不是新建