对象
想到对象,首先做如下创建:
var p1 = {
name: 'xyx',
age: 22,
sayname: function(){
console.log(this.name);
}
};
p.sayname();//xyx
可是如果要创建很多个,则要重复以上代码很多次,现创建一个函数,通过调用函数来创建对象:
工厂模式
function people(name,age){
var p = {
name: name,
age: age,
sayname: function(){
console.log(this.name);
}
};
return p;//引用类型,返回地址
}
var p1 = people("aa",11);
p1.sayname();//aa
var p2 = people("bb",11);
p.sayname();//bb
构造函数模式
function people(name,age){
this.name = name,
this.age = age,
this.sayname = function(){
console.log(this.name);
}
};
var p1 = new people("aa",11);
p1.sayname();//aa
console.log( p1 instanceof people ); //true
注:
1.people是个函数, 当 new people()的时候就会把people做为构造函数,构造对象。
2.用people创建对象后,people函数里的this代表 people {name: "aa", age: 11}.
3.instanceof的作用是判断p1是不是people的实例
原型方式
1.函数也是对象,对象是有属性和值的,任何一个函数都有prototype这个属性,这个属性的值也是对象,叫原型对象
2.当创建一个对象后,该对象拥有创建者赋予的所有功能。同时该对象还有个额外的内部属性,指向构造函数的原型对象。
3.把所有对象使用的公共资源放在原型对象。
4.原型属性:prototype;对象属性:__proto __
//创建一个Cake函数
function Cake(color,meterial){
this.color = color;
this.meterial = meterial;
}
//为Cake创建原型对象
Cake.prototype = {
other: '蜡烛',
sayname: function(){
console.log("我是"+this.color+this.meterial);
}
}
var c1 = new Cake("红色","五仁");
c1.sayname();//我是红色五仁
对于c1和cake存在以下关系:
Cake.prototype===c1.__proto__;//Cake {}
Cake.__proto__;//function (){}
Cake.constructor;//Function() { [native code] }
Cake.prototype.__proto__ === c1.__proto__.__proto__;//Object {}
c1.prototype;//undefinded 对象没有prototype属性
c1.constructor === Cake.prototype.constructor;//function cake(){}
下面有这样一段例子:
//先找cake函数里的sayname,如果没有则是prototype里的sayname函数
function Cake(color,meterial){
this.color = color;
this.meterial = meterial;
this.sayname= function(){
console.log(this.color+this.meterial);
}
}
Cake.prototype.sayname = function(){
console.log("我是"+this.color);
}
var c1 = new Cake("红色","五仁");//new一个c1对象后,cake里面的this指向c1
c1.sayname();//红色五仁
继承
原型链对象继承:
function People(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
People.prototype.say = function(){
console.log(this.name + "在说话");
}
Student.prototype = new People();//继承people原型链创建的方法
Student.prototype.constructor = Student;
function Student(name,age,sex,grade){
People.call(this,name,age,sex);
this.grade = grade;
}
var s1 = new Student("小妹",11,"女",88);
数据继承(用于默认参数)
var p1 = {name: '小灰', age: 1},
p2 = {name: '小呆', sex: 'male'};
var newObj1 = $.extend(obj1, obj2); //会把obj2合并覆盖到obj1,obj1被改掉
var newObj2 = $.extend({}, obj1, obj2); //不会改掉obj1,将obj1、obj2合并到{}
网友评论