如何自定义原型链接(构造函数)?

时间:2018-06-08 01:45:58

标签: javascript

我正在研究javascript链接但我无法根据需要设置构造函数。

function a() {}
function b() {}
function c() {}

a.prototype.text1 = 'text1';
b.prototype.text2 = 'text2';
c.prototype.text3 = 'text3';

a.prototype.constructor = b;
b.prototype.constructor = c;

var foo = new a();

console.log(foo.text1) // it`s output 'text1'. yea~ it`s right!
// But...
console.log(foo.text3) // it`s output undefined. My intention was output 'test3'.

为什么会这样? 我该怎么办?

请帮忙。感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用Object.create()



function a() {}
function b() {}
function c() {}

c.prototype.text3 = 'text3';

b.prototype = Object.create(c.prototype);
b.prototype.text2 = 'text2';

a.prototype = Object.create(b.prototype);
a.prototype.text1 = 'text1';

var foo = new a();

console.log(foo.text1);
console.log(foo.text2);
console.log(foo.text3);




Object.create()基本上将其原型创建为另一个对象的原型。

执行a.prototype.constructor = b之类的操作只是将constructor属性设置为b,而不是将b的原型添加到a

如果您了解ES6语法,则更容易理解(虽然结果在技术上并不相同):



class C {
  constructor(){
    this.text3 = 'text3';
  }
}

class B extends C {
  constructor(){
    super();
    this.text2 = 'text2';
  }
}

class A extends B {
  constructor(){
    super();
    this.text1 = 'text1';
  }
}

var foo = new A();

console.log(foo.text1);
console.log(foo.text2);
console.log(foo.text3);




修改

Object.assign()是更合适的方式。



function a() {}
function b() {}
function c() {}

c.prototype.text3 = 'text3';

b.prototype = Object.assign(c.prototype);
b.prototype.text2 = 'text2';

a.prototype = Object.assign(b.prototype);
a.prototype.text1 = 'text1';

var foo = new a();

console.log(foo.text1);
console.log(foo.text2);
console.log(foo.text3);




答案 1 :(得分:0)

您可以尝试探索Behaviour Delegation,并抛弃所有丑陋的原型样板。实现您的目标的一个例子如下:

let obj1 = {
  text1: 'Text 1'
}
let obj2 = Object.create(obj1)
obj2.text2 =  'Text 2';
let obj3 = Object.create(obj2)
obj3.text3 =  'Text 3';

let foo = obj3;
console.log(foo.text1)//Text 1
console.log(foo.text2)//Text 2
console.log(foo.text3)//Text 3

上面的代码称为OLOO样式(Object Linked To Another Object)而不是Prototype样式

这是另一个link,可以同时显示这两个代码进行比较