javascript_创建对象

//javascript_创建对象

//--------------------------------------代码1:
'use strict'
// 原型对象:
var Student = {
    name: 'Robot',
    height: 1.2,
    run: function () {
        console.log(this.name + ' is running...');
    }
};
function createStudent(name) {
    // 基于Student原型创建一个新对象:
    var s = Object.create(Student);
    // 初始化新对象:
    s.name = name;
    return s;
}
var xiaoming = createStudent('小明');
xiaoming.run(); // 小明 is running...
xiaoming.__proto__ === Student; // true
//--------------------------------------代码1解说:
//1.基于原型创建对象

//--------------------------------------代码2:
'use strict'
function Student(name) {
    this.name = name;
    this.hello = function () {
        alert(name + ' says:hello!');
    };
}
var stu1 = new Student('xiaoma');
console.log(stu1);
stu1.hello();
//--------------------------------------代码2解说:
//1.基于构造函数创建对象

//--------------------------------------代码3:
'use strict'
function Student(props) {
    this.name = props.name || '匿名'; // 默认值为'匿名'
    this.grade = props.grade || 1; // 默认值为1
}
Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
};
function createStudent(props) {
    return new Student(props || {})
}
var student = createStudent(
    {
        name: '小米',
        grade:1
    }
);
student.hello();
//--------------------------------------代码3解说:
//1.一个典型的创建对象的编程方法

  

猜你喜欢

转载自www.cnblogs.com/mexding/p/8990966.html