gpt4 book ai didi

JavaScript 将原型(prototype)添加到现有对象

转载 作者:行者123 更新时间:2023-11-30 12:21:20 25 4
gpt4 key购买 nike

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) 是一个对象,如果我在原型(prototype)行之前进行控制台。我上面的代码有什么问题?

最佳答案

看起来你真的只是想给 va 添加一个属性:

va.b = "Hey b is added";

如果,但是,您想要扩充 va 已有的原型(prototype),您可以通过引用 va 的原型(prototype)来实现对象,您可以通过多种方式获得:

  • 根据上面的代码,通过 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>

请注意,向原型(prototype)添加属性意味着所有使用该原型(prototype)的对象都将继承该属性:

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 将原型(prototype)添加到现有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30956307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com