当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS中的函数与对象

JS中的函数与对象

2019年05月13日  | 移动技术网IT编程  | 我要评论

创建函数的三种方式

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();

对象代码运行结果

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网