JS中的函数与对象的创建方式
网络编程 2021-07-04 15:50www.168986.cn编程入门
这篇文章主要介绍了JS中的函数与对象的创建方式,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
创建函数的三种方式
1.函数声明
function calSum1(num1, num2) { return num1 + num2; } console.log(calSum1(10, 10));
2.函数表达式
var calSum2 = function (num1, num2) { return num1 + num2; } console.log(calSum2(10, 20));
3.函数对象方式
var calSum3 = new Function('num1', 'num2', 'return num1 + num2'); console.log(calSum3(10, 30));
创建对象的三种方式
1.字面量方式
var Student1 = { name: 'xiaofang', // 对象中的属性 age: 18, sex: 'male', sayHello: function () { console.log('hello,我是字面量对象中的方法'); }, doHomeword: function () { console.log("我正在做作业"); } }; console.log(Student1); console.log(Student1.name); Student1.sayHello();
2.工厂模式创建对象
function createStudent(name, age, sex) { var Student = new Object(); Student.name = name; Student.age = age; Student.sex = sex; Student.sayHello = function () { console.log("hello, 我是工厂模式创建的对象中的方法"); } return Student; } var student2 = createStudent('小红', 19, 'female'); console.log(student2); console.log(student2.name); student2.sayHello();
3.利用构造函数创建对象(常用)
function Student (name, age, sex) { this.name = name; this.age = age; this.sex = sex; this.sayHello = function () { console.log("hello, 我是利用构造函数创建的对象中的方法"); } } var student3 = new Student('狼蚁网络推广', 20, 'male'); console.log(student3); console.log(student3.name); student3.sayHello();
对象代码运行结果
总结
以上所述是长沙网络推广给大家介绍的JS中的函数与对象的创建方式,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,长沙网络推广会及时回复大家的!
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程