JS中的函数与对象的创建方式
2019/6/26 23:04:03
本文主要是介绍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中的函数与对象的创建方式,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
这篇关于JS中的函数与对象的创建方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-03-30[OIDC in Action] 2. 基于OIDC(OpenID Connect)的SSO(纯JS客户端)
- 2024-03-29terraform jsonencode
- 2024-03-13vuex-persist
- 2024-03-11icons for vue
- 2024-03-07breadcrumbs react js
- 2024-03-06react login page example
- 2024-03-06react router uselocation
- 2024-03-04postgres jsonb_set
- 2024-03-01react native uuid
- 2024-02-29vuejs sidebar