我正在通过对象工作,我在codeacademy上遇到了这个例子,bob已经预先完成了,我的目标是复制susan并将她的年龄设置为35岁。我更喜欢使用字面符号,但我得到了错误(susan.setAge不是函数)。为什么现在还没有将setAge识别为函数?
// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;
// make susan here, and first give her an age of 25
var susan = {
age: 25
};
// here, update Susan's age to 35 using the method
susan.setAge(35);
答案 0 :(得分:2)
您还需要为Susan定义setAge()
方法:
// here we define our method using "this", before we even introduce bob
var setAge = function(newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;
// make susan here, and first give her an age of 25
var susan = {
age: 25,
setAge: setAge
};
// here, update Susan's age to 35 using the method
susan.setAge(35);
console.log(susan.age);
答案 1 :(得分:0)
如果您想在对象之间共享功能,可以创建一个class
并从该类创建实例。 JavaScript使用prototypes
来实现此目的:
var Person = function(name, age) {
this.name = name;
this.age = age;
};
Person.prototype.setAge = function(age){
this.age = age;
};
var bob = new Person("Bob", 35);
bob.setAge(40);
var susan = new Person("Susan", 30);
susan.setAge(25);
这样你就可以重用你的对象了。 如果您想要一次性对象使用
创建它们 var obj = {};
但是如果您想重用对象并将它们分组到一个类中,请在相应的prototype
上定义一个类及其方法。
您仍然可以向对象添加单个方法,即使它有原型:
susan.setName = function(name){ this.name = name; } // now only the susan object has this function
在https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes
了解有关原型的更多信息