构造函数

 

定义:

所谓的构造函数,其实就是一个普通的函数,但是内部使用了this变量。对构造函数使用new运算符,就能生成实例,并且this变量会绑定在实例对象上。

原型对象

function Student(name,sex){
    this.name = name;
    this.sex= sex;
}

实例对象

var student1 = Student("小明","男");
var student2 = Student("小红","女");
alert(student1.name);//小明
alert(student1.sex);//男

constructor属性

用于返回创建该对象的函数,也就是我们常说的构造函数。
这时cat1和cat2会自动含有一个constructor属性,指向它们的构造函数。

alert(student1.constructor == Student);//ture
alert(student2.constructor == Student);//ture

instanceof运算符

判断构造函数的原型对象(如:Cat.prototype和Object.prototype)是否在实例对象(cat1或cat2)的原型链上(proto)

alert(student1 instanceof Student);//ture
alert(student2 instanceof  Student);//ture

添加一个不变的属性或方法,如果直接在原型对象上添加会多占用内存。

原型对象

function Student(name,sex){
    this.name = name;
    this.sex= sex;
    this.grade= "二年级";
    this.age= function(){alert("8岁");};
}

实例对象

var student1 = new Student("小明","男");
var student2 = new Student("小红","女");
alert(student1.grade); // 二年级
student1.age(); // 8岁

表面上没有什么问题,但实际上这样做,有很大的弊端。对于每一个实例对象,唯一的属性和方法都一模一样的内容,每一次生成一个实例,都必须为重复内容,多占用一些内存,这样既不环保,也缺乏效率。

alert(student1.age == student2.age); //false

所以我们要让所有的实例都指向一个内存地址

prototype属性

JavaScript规定,每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有属性和方法,都会被构造函数的实例继承。
这意味着,我们可以把那些不变的属性和方法,直接定义在prototype对象上。

原型对象

function Student(name,sex){
    this.name = name;
    this.sex= sex;
}
Student.prototype.grade= "二年级";
Student.prototype.age= function(){alert("8岁")};

实例对象

var student1 = new Student("大毛","黄色");
var student2 = new Student("二毛","黑色");
alert(student1.grade); // 二年级
student1.age(); // 8岁

不变的属性和方法都是同一个内存地址,指向prototype对象,因此提高了运行效率

alert(student1.age == student2.age); //true

Prototype模式的验证方法

isPrototypeOf()

用来判断要检查其原型链的对象是否存在于指定对象的实例中。

alert(Student.prototype.isPrototypeOf(student1)); //true
alert(Student.prototype.isPrototypeOf(student2)); //true

hasOwnPrototype()

用来判断一个对象是否有你给出名称的属性或对象。注:此方法无法检查该对象的原型链中是否具有该属性,该属性必须是对象本身的一个成员

alert(student1.hasOwnProperty("name")); // true
alert(student1.hasOwnProperty("grade")); // false

in运算符

判断某个实例是否含有某个属性

alert("name" in student1); // true
alert("grade" in student1); // true

还可以用来遍历某个对象的所有属性

for(var prop in student1) { 
    alert("student1["+prop+"]="+student1[prop]); 
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值