javascript_create object

//javascript_create object

//-------------------------------------- Code 1:
'use strict'
// prototype object:
var Student = {
    name: 'Robot',
    height: 1.2,
    run: function () {
        console.log(this.name + ' is running...');
    }
};
function createStudent(name) {
    // Create a new object based on the Student prototype:
    var s = Object.create(Student);
    // Initialize the new object:
    s.name = name;
    return s;
}
var xiaoming = createStudent ('Komei');
xiaoming.run (); // Akari is running ...
xiaoming.__proto__ === Student; // true
//--------------------------------------Code 1 explanation:
//1. Create an object based on the prototype

//--------------------------------------Code 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();
//-------------------------------------- Code 2 explanation:
//1. Create an object based on the constructor

//--------------------------------------Code 3:
'use strict'
function Student(props) {
    this.name = props.name || 'anonymous'; // default is 'anonymous'
    this.grade = props.grade || 1; // default value is 1
}
Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
};
function createStudent(props) {
    return new Student(props || {})
}
var student = createStudent (
    {
        name: 'Xiaomi',
        grade:1
    }
);
student.hello();
//--------------------------------------Code 3 explanation:
//1. A typical programming method for creating objects

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325346183&siteId=291194637