使用Object.create()进行JavaScript继承? [英] JavaScript inheritance with Object.create()?

查看:204
本文介绍了使用Object.create()进行JavaScript继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Object.create()继承?我试过这些,但都没有工作:

How do I inherit with the Object.create()? I tried these, but none are working:

var B = function() {};
var A = function() {};
A = Object.create(B);
A.prototype.C = function() {};

var B = function() {};
var A = function() {};
A.prototype.C = function() {};
A = Object.create(B);

var B = function() {};
A = Object.create(B);
var A = function() {};
A.prototype.C = function() {};

没有任何效果。我该如何使用这个新的Object.create() - 函数?

Nothing worked. How am I supposed to use this new Object.create()-function?

推荐答案

Object.create ()用于继承对象,而不是像你想要的那样构造。它几乎创建了一个新对象,旧对象设置为原型父对象。

Object.create() is used to inherit objects, not constructors like you're trying to do. It pretty much creates a new object with the old object set as its prototypal parent.

var A = function() { };
A.prototype.x = 10;
A.prototype.say = function() { alert(this.x) };

var a = new A();
a.say(); //alerts 10

var b = Object.create(a);
b.say(); //alerts 10
b.x = 'hello';
b.say(); //alerts 'hello'

并且只是为了确保b不仅仅是a的克隆,

And just to make sure b is not just a clone of a,

a.x = 'goodbye';
delete b.x;
b.say(); //alerts 'goodbye'

这篇关于使用Object.create()进行JavaScript继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆