javascript对象中的方法问题
function person(firstname,lastname,age,eyecolor) {
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName=changeName;
function changeName(name) {
this.lastname=name;
}
}
var cont="";
myMother=new person("Steve","Jobs",56,"green");
myMother.changeName("Ballmer");
for (var i in myMother){
cont+=i+":"+myMother[i]+"<br />";
}
document.write(cont);
本人新手,在对JS中的对象方法的调用中对例子产生疑惑,JS中调用方法直接用object.method()就行了,为什么在上面代码中还需要添加这一句代码呢
this.changeName=changeName;
如果把这一句删除了就会显示
myMother.changeName is not a function
为什么需要在person中添加1个changeName 属性才行呢?
xiaokai
9 years, 2 months ago
Answers
function person(firstname,lastname,age,eyecolor) {
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
//加了这个语句后,声明的函数绑定到new操作符生成的对象的changName属性上,因为有其它变量引用到,故其不会被销毁掉
this.changeName=changeName;
//不加this.changeName=changeName;那么只是在person函数内部声明了一个函数,是一个person作用域范围内容的局部变量,而这个函数在person方法被调用后会被销毁掉
function changeName(name) {
this.lastname=name;
}
}
等价写法为
function person(firstname,lastname,age,eyecolor) {
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName=function(name) {
this.lastname=name;
}
}
复仇的黑百合
answered 9 years, 2 months ago
这个是js的构造函数问题( http://segmentfault.com/a/1190000002983180#articleHeader5 )
旺仔牛奶丶
answered 9 years, 2 months ago
function person(firstname, lastname, age, eyecolor) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.eyecolor = eyecolor;
//this.changeName=function(name) {
// this.lastname = name;
// }
}
person.prototype.changeName = function (name) {
this.lastname = name;
}
var cont = "";
myMother = new person("Steve", "Jobs", 56, "green");
myMother.changeName("Ballmer");
for (var i in myMother) {
cont += i + ":" + myMother[i] + "<br />";
}
alert(cont)
this.changeName=changeName
只是另外一种写法,这里涉及到原型。
JavaScript 不包含传统的类继承模型,而是使用 prototype 原型模型。
G線上D瀉藥
answered 9 years, 2 months ago