构造函数:就是一个构造对象的函数
特点:
1.函数名首字母大写
2.指向实例化的对象(谁new-this指向谁
<script>
/* 构造函数:就是一个构造对象的函数
特点:
1.函数名首字母大写
2.指向实例化的对象(谁new-this指向谁
*/
function Person(name,age){
this._name =name;
this._age =age;
}
/* 使用new关键字就可以实例化一个对象了 */
var p =new Person("lss",18);
var li = new Person("lisi",17);
console.log(p)
console.log(li)
/*
构造函数(类) --学生 -一类事物的抽象
对象 --实际的对象 --类的示例
*/
</script>
1-1. Array 构造函数
*****
<script>
/* Array 构造函数--数组类 */
/* 在数组的原型上定义了一个say,那么所有的实例都会拥有一个say */
Array.prototype.say = function(){
console.log("say")
}
var arr = new Array(1,2,3);
arr.push(5);
console.log(arr);
arr.say();
var res =[];
res.say();
</script>
******
<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=[3,4,5,6];
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>
可封装到一个js文件复用
*****
Array.prototype.sum =function(){
var s =0;
for(var i=0;i<this.length;i++){
s+=this[i];
}
return s
}
Array.prototype.remove =function(val){
var index =this.indexOf(val);
this.splice(index,1);
return this;
}
*****
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="array.js"></script>
</head>
<body>
<script>
var arr =[3,4,56];
console.log(arr.sum());
arr.remove(4);
console.log(arr)
</script>
</body>
</html>
1.构建函数必须通过new关键字才可以调用
2.this指向实例化的对象
<script>
/* 1.构建函数必须通过new关键字才可以调用 */
/* 2.this指向实例化的对象 */
function Student(name,age,skill){
this.name = name;
this.age = age;
this.skill = skill;
}
Student.prototype.sayName =function(){
console.log(this.name)
}
Student.prototype.saySkill =function(){
console.log(this.skill)
}
var p = new Student("lisi",18,"web");
console.log(p)
p.sayName();
p.saySkill();
</script>