function abc(){
this.a = "Hey this is A";
}
var va = new abc();
va.prototype = function(){
this.b = 'Hey b is added';
}
console.log(va.b);
va.b
是未定义的,我以为我已经将其添加到va
?因为console.log(va)
是对象,如果我在原型行之前进行控制台。我上面的代码有什么问题? 最佳答案
似乎您真的只想向va
添加属性:
va.b = "Hey b is added";
但是,如果您想扩充
va
已经拥有的原型,则可以通过引用va
的原型对象来做到这一点,可以通过以下几种方式获得它:通过上面的代码,通过
abc.prototype
或在ES5 +浏览器上,通过
Object.getPrototypeOf(va)
因此,例如:
function Abc() {
this.a = "Hey this is A";
}
var va = new Abc();
snippet.log(va.a); // "Hey this is A"
snippet.log(va.b); // undefined
Abc.prototype.b = 'Hey b is added';
snippet.log(va.b); // "Hey b is added"
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
注意,向原型添加属性意味着使用该原型的所有对象都将继承该属性:
function Abc() {
this.a = "Hey this is A";
}
var a1 = new Abc();
var a2 = new Abc();
Abc.prototype.b = 'Hey b is added';
snippet.log(a1.b); // "Hey b is added"
snippet.log(a2.b); // "Hey b is added"
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
关于javascript - JavaScript将原型(prototype)添加到现有对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30956307/