使用原型(prototype)有什么意义?如果我将类(class)设置为 -
var myClass = function(){ this.p1 = 'p1';}
现在如果我想将新属性添加为 p2
我为类做原型(prototype)属性,也在对象上做,比如
使用直接宾语->
var obj = new myClass();
obj.p2 = 'p2';
使用原型(prototype) ->
myClass.prototype.p2 = 'p2';
这两个有什么区别?还是两条线都不同?
最佳答案
Prototype 帮助你,拥有一种继承(prototypal inheritance)。
您可以手动向对象添加属性,或从其原型(prototype)中借用属性。让我们看一些例子:
var obj = new myClass();
obj.p2 = 'p - child';
console.log(obj.p2); // p - child
var obj2 = Object.assign(obj.__proto__); // will borrow the value from the obj prototype
console.log(obj.p2); // p - child
现在看看 myClass 原型(prototype)发生了什么:
var obj3 = Object.assign(myClass.prototype); //will borrow the value from the myClass prototype
console.log(obj3.p2); // p - parent
这里是一个不存在属性的例子:
var obj4 = new myClass();
var obj5 = Object.assign(obj4.__proto__);
obj4.p3 = 'P3 - value';
console.log(obj4.p3); // P3 - value
console.log(obj5.p3); // undefined
注意:__proto__
用于对象{},原型(prototype)用于函数。
希望这有助于澄清一点。
关于javascript - class.prototype.property 和 object.property 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48656332/