[英]Function as a prototype's objects's property in Javascript?
I have a code similar to this: 我有类似的代码:
var thing = function (prop1, prop2, prop3) {
this.prop1 = prop1;
this.prop2 = prop2;
this.prop3 = prop3;
};
function assignProp1 () {
return 'value1'; //Function simplified for the question
}
function generateThing () {
return new thing(function () {return assignProp1();}, 'value2', 'value3');
}
What I want to do is create different objects from the protoype "thing". 我要做的是从原型“事物”创建不同的对象。 But the code, instead of accepting 'value1' as prop1, returns "generateThing/<()" as prop1.
但是该代码不是将'value1'接受为prop1,而是将“ generateThing / <()”作为prop1返回。 I don't understand why it doesn´t work.
我不明白为什么它不起作用。
var thing = function (prop1, prop2, prop3) {
this.prop1 = prop1;
this.prop2 = prop2;
this.prop3 = prop3;
};
function assignProp1 () {
return 'value1'; //Function simplified for the question
}
function generateThing () {
return new thing( assignProp1(), 'value2', 'value3');
}
If you try to generate object where prop1 is a function, returning "value1" your code should work fine. 如果您尝试生成prop1是函数的对象,则返回“ value1”您的代码应该可以正常工作。 If you want object with prop1 = "value1" - first answer is good to you
如果您想要prop1 =“ value1”的对象-第一个答案对您有好处
Now if you add 现在,如果您添加
thing1 = generateThing();
console.log(thing1.prop1());
you will see a "value1" in console 您将在控制台中看到一个“ value1”
here is a snippet: 这是一个片段:
var thing = function (prop1, prop2, prop3) { this.prop1 = prop1; this.prop2 = prop2; this.prop3 = prop3; }; function assignProp1 () { return 'value1'; //Function simplified for the question } function generateThing () { return new thing(function () {return assignProp1();}, 'value2', 'value3'); } thing1 = generateThing() $("#out").text(thing1.prop1())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <span id="out"> </out>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.