一、初识
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>构造函数(类)</title>
<script type="text/javascript">
function Person(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
this.sayHello = function(){
console.log("你好,我叫"+name);
};
}
var xiaobai = new Person("小白",18,"男");
xiaobai.sayHello();
console.log("\n");
console.log("-----下面输出xiaobai的属性-----");
for(var i in xiaobai){
console.log(i+":"+xiaobai[i]);
}
console.log("\n");
console.log("-----下面输出console.log(xiaobai)-----");
console.log(xiaobai);
console.log("\n");
console.log("xiaobai instanceof Person = "+(xiaobai instanceof Person));
console.log("xiaobai instanceof Object = "+(xiaobai instanceof Object));
console.log("window instanceof Object = "+(window instanceof Object));
</script>
</head>
<body>
</body>
</html>
这是我自己的理解,如果有错以后再改
二、解决一中存在的问题
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>构造函数2</title>
<script type="text/javascript">
function Student(name,age,gender){
this.name = name;
this.age = age;
this.gender = gender;
this.sayHello = function(){
console.log("大家好,我是"+this.name);
};
}
var stu1 = new Student("小白",18,"男");
var stu2 = new Student("小红",18,"女");
console.log(stu1.sayHello == stu2.sayHello);
function Dog(name,age){
this.name = name;
this.age = age;
this.eat = dogEat;
}
function dogEat(){
console.log(this.name+"在吃饭。");
};
var xiaohei = new Dog("小黑",2);
var wangcai = new Dog("旺财",1);
console.log("-----测试eat-----")
xiaohei.eat();
console.log("-----比较两个实例的eat是不是同一个-----")
console.log(xiaohei.eat == wangcai.eat);
</script>
</head>
<body>
</body>
</html>