var p = new Object();
p.name = "Tom";
p.age = 12;
p.setName = function(name) {
this.name = name;
};
var p = {
name: "Tom",
age: 12,
setName: function(name) {
this.name = name
}
};
//返回一个对象的函数--->工厂函数
function createPerson(name, age) {
var obj = {
name: name,
age: age,
setName: function(name) {
this.name = name;
}
};
return obj;
};
function createStudent(name, price) {
var obj = {
name: name,
price: price,
setName: function(name) {
this.name = name;
}
};
return obj;
};
var person = createPerson("Bob",12);
var student= createStudent("Mary",12000);
//person student都是object类型
function Person(name, age) {
this.name = name;
this.age = age;
this.setName = function(name) {
this.name = name;
};
}
function Student(name, price) {
this.name = name;
this.price = price;
}
var person = new Person("Bob", 12);
console.log(person instanceof Person);// true
var student = new Student("Mary", 12000);
console.log(student instanceof Student);// true
function Person(name, age) {
//在构造函数中只初始化一般函数
this.name = name;
this.age = age;
};
Person.prorotype.setName = function(name) {
this.name = name;
};
var p1 = new Person("Tom", 23);
var p2 = new Person("Jack", 24);
(1)方式
//父类型
function Supper() {
this.supProp = "Supper property";
}
Supper.prototype.showSupperProp = function() {
console.log(this.supProp);
};
//子类型
function Sub() {
this.subProp = "Sub property";
}
//子类型的原型为父类型的一个实例对象
Sub.prototype = new Supper();
//让子类型的原型的constructor指向子类型
Sub.prototype.constructor = Sub;
Sub.prototype.showSubProp = function () {
console.log(this.subProp);
}
var sub = new Sub();
sub.showSupperProp();
sub.showSubProp();
(1)方式:
function Person(name, age) {
this.name = name;
this.age = age;
}
function Student(name, age, price) {
Person.call(this, name, age);// 相当于:this.Person(name, age);这里的this为Student的实例对象
//this.name =name;
//this.age = age;
this.price = price;
}
var s = new Student("Tom", 20, 12000);
console.log(s.name, a.sge, s.price);
(1)方式:原型链+借用构造函数的组合继承
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.setName = function(name) {
this.name = name;
}
function Student(name, age, price) {
Person.call(this, name, age);
this.price = price;
}
Student.prototype = new Person();// 为了能看到父类型的方法
Student.prototype.constructor = Student;//修正constructor属性,否则指向Person
Student.prototype.setPrice = function(price) {
this.price = price;
}
var s = new Student("Tom", 20, 12000);
s.setName("Bob");
s.setPrice(14000);
console.log(s.name, a.sge, s.price);//Bob 20 14000