<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function people(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
this.sleep=function (){
return "睡觉";
};
this.eat=function (){
return "吃饭";
}
}
var p = new people('张三','21','男');
console.log(p);
function work(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
this.sleep = function(){
return "睡觉奥";
};
this.eat = function(){
return "吃饭";
}
}
var w = new work("大壮",31,"男");
console.log(w);
//建立一个ew的匿名函数
var New = function(o){
var obj = {};//创建一个基本对象
obj.__proto__ = o.prototype;//对象的原型链 = 函数的原型对象
o.prototype.constructor = o;//函数的原型对象的构造函数指向本身
//考虑函数的属性和方法 以及传递的参数
var args = Array.prototype.slice.call(arguments,1);
o.apply(obj,args);
return obj;
}
var maodou = New(people,"maodou",15,"男");
console.log(maodou);
//面试题 自己写一个排序,用数组来执行
Array.prototype.mySort = function(){
return this.sort();
}
var str = [2,4,5,1,7,8,6];
console.log(str.mySort());
//函数的原型对象
function Animal(){
}
console.log(Animal.prototype);//输出的是当前函数的原型对象
console.log(Animal.prototype.constructor);//输出的是当前函数原型对象的构造函数 指向本身
/*原型对象上面可以写入原型方法和原型属性
* 1.原型属性
* Animal.prototype.name = null;
* Animal.prototype.age = null;
* Animal.prototype.sex = null;
* 2.原型方法
* Animal.prototype.sleep = function(){console.log("睡觉");};
* Animal.prototype.eat = function(){console.log("吃饭");};
* console.log(Animal.prototype);
* */
//例如:
Animal.prototype = {
constructor:Animal,
name:"",
age:"",
sex:"",
sleep:function(){
},
eat:function(){
}
}
console.log(Animal.prototype);
//原型对象上的属性方法 全是共享的
var cat = new Animal();
console.log(cat);
var mouse = new Animal();
console.log(mouse);
</script>
</body>
</html>
JS使用函数创建对象
最新推荐文章于 2022-08-16 17:21:32 发布