在实例化变量时,很容易将变量传递给新对象。例如,下面的代码非常完美。
var CreatureStory, zombie;
function CreatureStory(species, action) {
this.species = species;
this.action = action;
this.story = function() {
console.log('The ' +this.species +' is about to ' +this.action +'.');
}
}
zombie = new CreatureStory('zombie', 'walk'); //variables passed in here.
zombie.story(); // But how would I pass them in here?

但是,如果我需要在创建对象后将它们传递给对象怎么办?例如,下面的代码不会将变量放入已创建的对象中。它们的值显示为undefined
。
zombie.story('zombie', 'walk');
答案 0 :(得分:2)
您必须将参数传递给var CreatureStory, zombie;
function CreatureStory(species, action) {
this.species = species;
this.action = action;
this.story = function(species, action) { // Like this !!!!
this.species = species;
this.action = action;
console.log('The ' +this.species +' is about to ' +this.action +'.');
}
}
zombie = new CreatureStory('zombie', 'walk'); //variables passed in here.
zombie.story('monster', 'sleep'); // But how would I pass them in here?
方法。
species

此外,我更新action
和{{1}}属性以反映新值
答案 1 :(得分:1)
如果您的功能不接受任何参数,则无法为其添加参数。
您可以更改功能以接受参数;或在调用story
像:
var CreatureStory, zombie;
function CreatureStory(species, action) {
this.species = species;
this.action = action;
this.story = function() {
console.log('The ' +this.species +' is about to ' +this.action +'.');
}
}
zombie = new CreatureStory('zombie', 'walk');
zombie.action = 'run';
zombie.story(); // the zombie now will run

答案 2 :(得分:1)
创建后,您可以像这样为对象赋值: zombie.action ="坐"
Thien zombie.story()将返回"这个僵尸即将坐下来#34;
答案 3 :(得分:1)
将this.species
和this.action
更改为var species
和var action
var CreatureStory, zombie;
function CreatureStory(species, action) {
var species = species;
var action = action;
this.story = function() {
console.log('The ' +species +' is about to ' +action +'.');
}
}
zombie = new CreatureStory('zombie', 'walk'); //variables passed in here.
zombie.story(); // But how would I pass them in here?
答案 4 :(得分:0)
如果我理解正确,你可以更新你的this.story函数,如下所示:
var CreatureStory, zombie;
function CreatureStory(species, action) {
this.species = species;
this.action = action;
this.story = function(species, action) {
species = species || this.species;
action = action || this.action;
console.log('The ' + species +' is about to ' + action +'.');
}
}
zombie = new CreatureStory('zombie', 'walk'); //variables passed in here.
zombie.story();
答案 5 :(得分:0)
我认为你应该尝试理解JavaScript中的原型继承:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
之前了解原型继承模型至关重要 编写利用它的复杂代码。另外,要注意 代码中原型链的长度,如果是,则将其分解 必须避免可能的性能问题。此外,原生 原型不应该延长,除非是为了 与较新的JavaScript功能兼容。
答案 6 :(得分:0)
componentWillReceiveProps(nextProps) {
if(nextProps.index == this.props.ordinalNumber) {
console.log("STARTING ANIMATION!!!");
Animated.timing(this.animatedValue, {
toValue: 1.5,
duration: 1000
}).start();
}
}