构造函数具有属性

时间:2017-03-14 14:58:13

标签: javascript

我对javascript构造函数prototipes有疑问。所以,如果我有这样的事情:

a = function (name){this.name = name};
a['b'] = function (age){this.age = age};
c = new a('John');
c.a['b'](30);

这可以吗?如果是, c 对象如何找到 a ['b'] 函数?它是否通过其 proto 属性并达到构造函数?构造函数是否在新创建的对象上设置 b 属性?

1 个答案:

答案 0 :(得分:2)

  

这可以吗?

不,它在最后一行失败并出错。 c对象没有a属性:



a = function (name){this.name = name};
a['b'] = function (age){this.age = age};
c = new a('John');
c.a['b'](30); // TypeError here




new a创建一个继承自a.prototype引用的对象的对象。 a.prototype没有a属性。

如果您希望从a转到ca.prototype的{​​{1}}属性会引用constructora继承那个属性,所以:

c

但是,这样做会调用c.constructor['b'](30); 引用this的第二个函数,从而在第一个函数中添加c.constructor属性:



age




退一步,整体结构

a = function (name){this.name = name};
a['b'] = function (age){this.age = age};
c = new a('John');
c.constructor['b'](30);
console.log(a.age); // 30

......没有多大意义。通常没有理由将a = function (name){this.name = name}; a['b'] = function (age){this.age = age}; c = new a('John'); 放在b上。

旁注:您的代码正在成为The Horror of Implicit Globals 的牺牲品(这是我贫血小博客上的帖子):声明您的变量。