🐚作者简介:苏凉(专注于网络爬虫,数据分析,正在学习前端的路上)
🐳博客主页:苏凉.py的博客 🌐系列总专栏:web前端基础教程 👑名言警句:海阔凭鱼跃,天高任鸟飞。
📰要是觉得博主文章写的不错的话,还望大家三连支持一下呀!!!
👉关注✨点赞👍收藏📂
文章目录
- 1.通过表达式创建
- 2.使用new关键字
- 3.使用工厂模式
- 4.使用构造函数
- 四种方法详解传送锚点
1.通过表达式创建
<!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>//1.通过表达式创建对象
var per1 = {
name:'苏凉',
age:21,
gender:'男',
sayName:function(){
console.log(this.name)
}
};
console.log(per1);
per1.sayName();</script>
</head>
<body>
</body>
</html>
2.使用new关键字
<!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>//2.使用new关键字
var per2 = new Object();
per2.name = '苏凉';
per2.age = 21;
per2.gender = '男';
per2.sayName = function(){
console.log(this.name)
}
console.log(per2);
per2.sayName();</script>
</head>
<body>
</body>
</html>
3.使用工厂模式
<!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>//3.使用工厂模式创建
function person(name,age,gender){
var obj = new Object();
obj.name = name;
obj.age = age;
obj.gender = gender;
obj.sayName = function(){
console.log(this.name)
}
return obj;
}
var per3 = person('苏凉',21,'男');
console.log(per3);
per3.sayName();</script>
</head>
<body>
</body>
</html>
4.使用构造函数
<!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>//4.使用构造函数创建
function Person(name, age,){
this.name = name ;
this.age = age ;
this.gender = gender;
}
Person.prototype.sayName = function(){
console.log(this.name)
}
var per4 = new Person('苏凉',21,'男');
console.log(per4);
per4.sayName();</script>
</head>
<body>
</body>
</html>
运行结果:
四种方法详解传送锚点
🚀1.web前端-JavaScript中的对象(Object)
🚀2. web前端-JavaScript使用工厂模式创建对象
🚀3. web前端-JavaScript构造函数创建对象
🚀4. web前端-JavaScript中的原型对象