国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

JS中的函數與對象的創建方式

2024-05-06 16:50:48
字體:
來源:轉載
供稿:網友

創建函數的三種方式

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中的函數與對象的創建方式,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 桐梓县| 麻栗坡县| 吴江市| 阿尔山市| 新晃| 汾西县| 开封县| 如皋市| 乌拉特前旗| 启东市| 滨海县| 九江县| 宁远县| 司法| 修文县| 保德县| 海安县| 富阳市| 精河县| 蒲江县| 高唐县| 江川县| 鄂托克前旗| 巨鹿县| 马关县| 册亨县| 图木舒克市| 伽师县| 左贡县| 磴口县| 隆安县| 伊春市| 阿合奇县| 资溪县| 临邑县| 饶平县| 正蓝旗| 奉新县| 雅安市| 宜阳县| 宜昌市|