<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>构造函数来创建对象,向构造函数的prototype中添加成员,实现数据在实例间共享</title>
</head>
<body>
<script>
var CreatPerson = function ( name,age,gender) {
this.name = name;
this.age = age;
this.gender = gender;
this.sayHi = function () {
console.log("Hi "+name)
};
};
CreatPerson.prototype.face=500; /*构造函数添加一个原型属性*/
var obj1 = new CreatPerson("孙悟空",18,"男");
console.log(obj1.name,obj1.age,obj1.gender);
console.log(obj1.sayHi());
console.log(obj1.face); /*对象可以调用原型属性*/
console.log("face" in obj1); //检查是不是有"face"这个属性,原型属性的也算在内。
console.log(obj1.hasOwnProperty("face")); //检查是不是有"face"这个属性,原型属性的不算在内。
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
构造函数为了方便你能够批量创建对象
创建一个新对象。
将构造函数的作用域赋给新对象。与此同时,this也就指向了这个对象。
执行构造函数中的代码。
原型属性可以实现对象实例共享其属性。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号