Javascript将原型添加到现有对象

时间:2015-06-20 16:25:42

标签: javascript

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

4 个答案:

答案 0 :(得分:2)

好像你真的只想在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>

答案 1 :(得分:1)

您可能只想将该属性添加到va

va.b = 'Hey b is added';

除非您希望将b属性添加到abc的所有实例,否则您可以将其添加到abc的原型中:

abc.prototype.b = 'Hey b is added';

答案 2 :(得分:0)

试试这个:

<script>
    function abc()
    {
        //constructor
        this.a="Hey this is A";
    }
    abc.prototype.b=function()
    {
        //prototype
        this.b='Hey b is added';
    };
    var va=new abc();//Initialization
    va.b();//value for b is assigned to the context
    console.log(va.b);
</script>

提供评论..

答案 3 :(得分:0)

您没有创建b属性,因为您从未调用va.prototype

function abc(){
 this.a = "Hey this is A";   
}
var va = new abc();
va.prototype = function(){
  this.b = 'Hey b is added';
};
va.b; // undefined
va.prototype();
va.b; // "Hey b is added"

请注意,使用prototype作为方法的名称可能会造成混淆(函数的prototype和对象的[[Prototype]]已经存在混淆。我建议选择其他名字。