1. 程式人生 > >JS中的函數與對象

JS中的函數與對象

構造 say eat sum 函數表達式 spa 小明 aof urn

創建函數的三種方式

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中的函數與對象