在Javascript中作为原型对象的属性?

时间:2015-05-21 15:16:15

标签: javascript function object prototype

我有类似的代码:

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'); 
}

我想要做的是从原型“事物”创建不同的对象。但是代码不是接受'value1'作为prop1,而是将“generateThing /<()”作为prop1返回。我不明白为什么它不起作用。

2 个答案:

答案 0 :(得分:0)

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'); 
}

答案 1 :(得分:0)

如果您尝试生成prop1为函数的对象,则返回" value1" 你的代码应该工作正常。如果你想要对象与prop1 =" value1" - 第一个答案对你有好处

现在,如果你添加

thing1 = generateThing();
console.log(thing1.prop1());

你会看到" value1"在控制台

这是一个片段:



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>
&#13;
&#13;
&#13;