以OOP的方式,我正在定义一个Person" class"如下:
var Person = {
name: '',
age: 32,
gender: 'male',
interests: ['music', 'skiing'],
bio: function() {
alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
},
greeting: function() {
alert('Hi! I\'m ' + this.name + '.');
}
};
现在,我正在实例化上面的类。
var person1= Object.create(Person);
person1.name = 'personname';
person1.greeting();
如何模仿构造函数,以便在Object.create(Person)创建新对象时,构造函数代码会自动计算?
答案 0 :(得分:1)
您将在函数中包装代码,并在那里调用它。 Object.create
会与prototype
建立关系,但不会自动调用任何其他代码。
function person(name) {
var person1 = Object.create(Person);
person1.name = name;
return person1;
}
person('personname').greeting();
除非它们是应该使用new
调用的函数,否则还应该避免对变量的第一个字母进行大写。这是一个仅用于构造函数的命名约定。
答案 1 :(得分:1)
您可以创建一个真正的类,以便与new
一起使用。
var Person = function () {
var Person = function () {
this.name = ['', ''];
this.age = 32;
this.gender = 'male';
this.interests = ['music', 'skiing'];
};
Person.prototype.bio = function() {
return this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.';
};
Person.prototype.greeting = function() {
return 'Hi! I\'m ' + this.name + '.';
};
return Person;
}();
var p1 = new Person;
p1.name = ['Tom', 'Sawyer'];
console.log(p1.bio());
console.log(p1);

答案 2 :(得分:0)
var Person = function(name) {
this.name = name || '';
this.age = 32;
this.gender = 'male';
this.interests = ['music', 'skiing'];
this.bio = function() {
alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
};
this.greeting = function() {
alert('Hi! I\'m ' + this.name + '.');
};
};
var person1= new Person('personname');
person1.greeting();