js 基础

1. 强制类型转换

1.1 其他数据类型转 String

  1. 使用 toString() 方法
var a = 123
var s = a.toString();
console.log(typeof s)
  1. 使用 String() 函数
var b = null
var s1 = String(b);
console.log(typeof s1)

1.2 其他数据类型转 Number

  1. 使用 Number() 函数
  2. 使用 parseInt() 函数
    parseInt 可以将一个字符串中有效的整数提取出来

2. 对象

2.1 对象的分类

在这里插入图片描述

2.2 创建对象

2.2.1 使用 new 构造函数创建

var obj = new Object()
// 为对象添加属性
obj.name = "zhangsan"
obj.age = 13
obj.say = function () {
    console.log("hello")
}

2.2.2 使用对象字面量

在这里插入图片描述

var obj1 = {
    name: "zhangsan",
    age: 18,
    say: function () {
        console.log("hello")
    },
    objj: {
        height: 189,
        weight: 90
    }

}
obj1.say()
console.log(obj1.objj.weight);

2.2.3 使用构造函数创建对象

2.2.3.1 构造函数 1.0

构造函数习惯上首字母大写

function Person(name) {
    this.name = name
    this.hello = function () {
        console.log(this.name)
    }
}
var person = new Person("zhangsan");
console.log(person.name)
person.hello()

构造函数的执行流程:

  1. 立刻创建一个新的对象
  2. 将新建的对象设置为函数中的 this, 在构造函数中使用 this 指向当前新创建的对象
  3. 逐行执行构造函数中的代码
  4. 将新建的对象作为返回值返回
2.2.3.2 构造函数 2.0
function Person2(name) {
    this.name = name;
}

Person2.prototype.hello = function () {
    console.log(this.name)
}

var person2 = new Person2("lisi");
person2.hello()

类似于静态, 将对象共有的属性方法抽取出去, 放入的原型对象中.

2.3 访问对象属性

2.3.1 使用 .

2.3.2 使用 [ ]

console.log(obj["age"])

3. 函数

3.1 函数创建

  1. 方式 1
function fun1() {
    console.log("hello function")
}
fun1()
  1. 方式 2
var fun2 = function () {
    console.log("hello function2")
}
fun2()

3.2 立即执行函数

(function (a,b) {
    console.log(a + b);
})(1,3)

4. class

function Student(name) {
    this.name = name;
}

Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
}

使用 class 实现

class Student {
    constructor(name) {
        this.name = name;
    }

    hello() {
        alert('Hello, ' + this.name + '!');
    }
}

class的定义包含了构造函数constructor和定义在原型对象上的函数hello()(注意没有function关键字),这样就避免了Student.prototype.hello = function () {…}这样分散的代码。
最后,创建一个Student对象代码和前面章节完全一样:

var xiaoming = new Student('小明');
xiaoming.hello();

class 继承

class PrimaryStudent extends Student {
    constructor(name, grade) {
        super(name); // 记得用super调用父类的构造方法!
        this.grade = grade;
    }

    myGrade() {
        alert('I am at grade ' + this.grade);
    }
}

5. 数组

5.1 创建数组

  1. new Array
var arr = new Array()
var arr2 = new Array(1,2,3)
var arr3 = new Array(10)
console.log(arr)

arr[0] = 'aa'
arr[1] = 21

  1. 字面量 [ ]
var arr2 = [1.2,3,'o']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值