创建函数的三种方式

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中的函数与对象的创建方式,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

标签:
js中的函数,js,对象

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com

评论“JS中的函数与对象的创建方式”

暂无“JS中的函数与对象的创建方式”评论...

P70系列延期,华为新旗舰将在下月发布

3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。

而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?

根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。