js类型为string|string

JavaScript030

js类型为string|string,第1张

1、js分为基本数据类型和引用数据类型

2、string定义为基本数据类型,但是既然为基本数据类型为什么还可以调用方法呢?

let a = "hello world"

a.name = "张三"

console.log(typeof a)

console.log(a)

3、string还有另外一种创建的方法 new String("hello world")

let b = new String("hello world")

b.name = "赵四"

console.log(typeof b)

console.log(b.substring(0, 2))

new出来的字符串则是对象类型,在我们打印的时候可以看到,调用方法的时候是通过原型进行调用方法的

4、在使用字符串方法的时候内部是就行new了的操作从而调用的方法。

可以在原型链上添加方法,一种可以在某一个string对象上添加方法,一种可以直接在数据类型string上面添加公用方法例如String.prototype.go = function(){//在string大对象上添加方法go

console.log(this)}'sss'.go()//会输出‘sss’本身

或者只是在某一个对象上添加方法var str = new String('sss')//新建一个string对象str.go = function(){//在这个对象那个身上添加方法console.log(this)}str.go()