基本对象的创建方式
var stu={
name:'zs',
age:12,
eat:function(){
// 在基本对象内部this指向的是当前的对象stu
console.log(this);
console.log(this.name)//zs
}
}
工厂方式创建对象
function Student(name,age){
return{
name:name,
age:age,
eat:function(){
console.log(this);
}
}
}
构造函数方式创建对象
function Student(name,age){
this.name=name;
this.age=age;
this.eat=function(){
console.log(this.name);
}
}
使用的时候先实例化构造函数var stu=new Student('zs',12);
其实用new创建新对象的过程经历了下面三步
/*
调用new关键字的时候,
第一步:首先生成一个空对象
第二步:构造函数中的this指向当前对象
第三步:执行构造函数代码
*/
但每次使用构造函数的方法都得实例化一个新对象,而方法又是一样的,造成资源的浪费。
构造函数+构造函数的原型方式创建对象
function Student(name,age){
this.name=name;
this.age=age;
}
Student.prototype.eat=function(){
console.log(this.name);
}
如果构造函数的原型被赋予新的值,则会丢失了constructor
Product.prototype={
// 可以手动加上constructor
//constructor:Product,
buy:function(){
console.log('buy')
},
joinCar:function(){
console.log('joinCar')
}
}
实例对象的__proto__指向构造函数的prototype,可以通过这个方法改写原型上的方法
function Product(title,color){
this.title=title;
this.color=color;
}
Product.prototype.buy=function(){
console.log('buy')
}
var product=new Product('小熊布偶','红色');
product.__proto__.buy=function(){
console.log('buyed')
}
实例对象.hasOwnProperty('属性')可以判断属性是自有的还是继承来的
function Product(title,color){
this.title=title;
this.color=color;
this.buy=function(){
alert('确认购买'+this.title)
}
}
Product.prototype.buy=function(){
console.log('buy')
}
Product.prototype.joinCar=function(){
console.log('加入购物车')
}
var p=new Product('口红','401');
console.log(p.hasOwnProperty("joinCar"))//false
console.log(p.hasOwnProperty("buy"))//true
使用 a instanceof b构造函数 判断a是否是通过b构造函数构造出来的
function Product(title,color){
this.title=title;
this.color=color;
this.buy=function(){
alert('确认购买'+this.title)
}
}
Product.prototype.buy=function(){
console.log('buy')
}
Product.prototype.joinCar=function(){
console.log('加入购物车')
}
var p=new Product('口红','401');
console.log(p instanceof Product);//true
console.log(p instanceof Object);//true
console.log(p instanceof Array);//false