Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript对象-不是一个函数_Javascript - Fatal编程技术网

Javascript对象-不是一个函数

Javascript对象-不是一个函数,javascript,Javascript,我正在研究对象,我在codeacademy上遇到了这个例子,bob是预先准备好的,我的目标是复制susan并将她的年龄设置为35岁。我更喜欢使用文字符号,但我得到一个错误(susan.setAge不是一个函数)。为什么它现在不承认设置是一个函数 // here we define our method using "this", before we even introduce bob var setAge = function (newAge) { this.age = newAge; }

我正在研究对象,我在codeacademy上遇到了这个例子,bob是预先准备好的,我的目标是复制susan并将她的年龄设置为35岁。我更喜欢使用文字符号,但我得到一个错误(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  
};
// here, update Susan's age to 35 using the method
susan.setAge(35);

您还需要为Susan定义
setAge()
方法:
//在介绍bob之前,我们先用“this”定义我们的方法
var setAge=函数(新年龄){
这个年龄=新年龄;
};
//现在我们让鲍勃
var bob=新对象();
年龄=30岁;
bob.setAge=设置;
//把苏珊带到这里,先给她25岁的年龄
变量susan={
年龄:25岁,
设置:设置
};
//在这里,使用以下方法将Susan的年龄更新为35岁
苏珊·塞塔吉(35岁);

console.log(susan.age)如果要在对象之间共享功能,可以创建一个
,并从该类创建实例。JavaScript使用
原型
实现此目的:

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={}

但是,如果要重用对象并将其分组到一个类中,请在相应的
原型
上定义一个类及其方法
您仍然可以向对象添加单独的方法,即使它有一个原型:

susan.setName=function(name){this.name=name;}//现在只有susan对象具有此函数


有关原型的更多信息,请访问:

这是因为susan不知道如何使用名为
setAge的方法。只有Bob有一个你从来没有在全局方法中添加过设置方法吗?不特定于bob?alice发生了什么事?@ChrisCundick:如果方法是全局的,那么为什么行
bob.setAge=setAge存在?在ES6中,
:设置是冗余的。