javascript_创建对象

Posted mexding

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.一个典型的创建对象的编程方法

  

以上是关于javascript_创建对象的主要内容,如果未能解决你的问题,请参考以下文章

Android 逆向使用 Python 解析 ELF 文件 ( Capstone 反汇编 ELF 文件中的机器码数据 | 创建反汇编解析器实例对象 | 设置汇编解析器显示细节 )(代码片段

Atom编辑器折腾记_(15)JS代码片段补全(插件:javascript-snippets)

javascript_创建对象

JavaScript 创建新对象

常用Javascript代码片段集锦

VSCode自定义代码片段——JS中的面向对象编程