1-1 对象
某一类事物的具体实例
1-2 类
对某一具体事物的抽象
1-3 构造函数
1-3-1 实例
实例: new 出来的对象
1-3-2 构造函数的缺点
同一个构造函数的多个实例之间,无法共享属性,从而造成对系统资源的浪费。
/* 公有的属性或者公有的方法我们可以放在原型对象上 */
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.eat = "水果"
var p = new Person("li",19)
var zhang = new Person("zhang",20)
console.log(p);
console.log(zhang);
1-3-3 构造函数
构造函数:构造一个类(对象)的函数
构造函数的特点:
1.首字母大写
2.函数内部使用this关键字,谁new(实例化)就指向谁
3.使用this关键字给对象添加属性
4.必须使用new关键字,去生成一个对象
// 在 javascript 中新建一个类 使用构造函数
function Student(name,age){
this.name = name;
this.age=age
}
/* this 指实例化的对象 */
/* 实例 */
var zheng = new Student("zcy",18)
console.log(zheng);
// 读取对象的属性
console.log(p.name);
console.log(p.age);
1-3-4 instanceof 判断一个对象是不是某个类的实例
var arr = [1,2,3]
console.log(arr instanceof Array); // true
function Person(name,age){
this.name = name
this.age = age
}
var p = new Person("zheng",18)
console.log(p instanceof Person); // true
构造函数例子
<script>
Array.prototype.push = function(){
console.log("失效了")
}
var arr = [];
arr.push(4);
console.log(arr)
/* remove(value) */
Array.prototype.remove= function(val){
var index = this.indexOf(val);
this.splice(index,1);
return this;
}
var arr = [5,6,7];
console.log(arr.remove(6));
/* sum */
Array.prototype.sum = function(){
var s= 0;
for(var i=0;i<this.length;i++){
s+=this[i];
}
return s;
}
var test = [1,2,3];
console.log(test.sum())
</script>
判断一个属性是自由的还是共有的
console.log(p.hasOwnPropery("kill"));