javascript 中没有类。话虽如此,您可以使用几种不同的方式模拟类。
使用函数并为其原型定义方法
var Person = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
// you can define Person.fullname = function() {} straight to the function
// drawback to this is fullname function will be created everytimg you create a new Person
// instead you can create fullname in the prototype of the Person so it only gets created once
Person.prototype.fullname = function() {
return this.firstName + ' ' + this.lastName;
};
var person = new Person('John', 'Doe');
person.fullname(); // John Doe
使用对象字面量
var Person = {
firstName: 'John',
lastName: 'Doe',
fullname: function() {
return this.firstName + ' ' + this.lastName;
}
};
Person.fullname(); // John Doe
Person.firstName = 'Jane';
Person.fullname(); // Jane Doe
使用单例
var person = new function() {
this.firstName = 'John';
this.lastName = 'Doe';
this.fullname = function() {
return this.firstName + ' ' + this.lastName;
};
};
person.fullname(); // John Doe
person.firstName = 'Jane';
person.fullname(); // Jane Doe
如果您打算更深入地了解java 类的工作原理、应用继承等,那么我建议您使用第一种方法。下面是使用prototype 的简单继承示例。
var Person = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
Person.prototype.fullname = function() {
return this.firstName + ' ' + this.lastName;
};
Person.prototype.getFirstName = function() {
return this.firstName;
};
Person.prototype.getLastName = function() {
return this.lastName;
};
Person.prototype.setLastName = function(lastName) {
return this.lastName = lastName;
};
Person.prototype.setFirstName = function(firstName) {
return this.firstName = firstName;
};
var Student = function(firstName, lastName, grade) {
this.grade = grade;
Person.call(this, firstName, lastName);
};
Student.prototype = Object.create(Person.prototype);
Student.prototype.getGrade = function() {
return this.grade;
};
var student = new Student('John', 'Doe', '5th');
student.fullname(); // John Doe
student.getFirstName(); // John
student.setFirstName('Jane');
student.getFirstName(); // Jane
student.getGrade(); // 5th
这应该解释了如何使用javascript 中的类,类似于你在java 中使用的类。
使用dot notation 和brackets 访问对象属性有什么区别?
简短的回答,两者的行为完全相同。但是在某些情况下dot notation 并不总是有效。例如:
var person = {
"first name": "john",
"last name": "doe",
"fullname": "john doe"
};
person.fullname; // john doe
// to access first name property of person
person.first name; // will not work
person["first name"]; // john