原始类型
ECMAScript 有 5 种原始类型(primitive type),即 Undefined、Null、Boolean、Number 和 String。
typeof 运算符
typeof 运算符有一个参数,即要检查的变量或值。
对变量或值调用 typeof 运算符将返回下列值之一:
- undefined - 如果变量是 Undefined 类型的
- boolean - 如果变量是 Boolean 类型的
- number - 如果变量是 Number 类型的
- string - 如果变量是 String 类型的
- object - 如果变量是一种引用类型或 Null 类型的
**注:**null 是对象的占位符。
类型之间的转换
- 转字符串: toString()
- 转数字: parseInt(string [,radix] ) 、parseFloat() 返回小数
- 转成Boolean:Boolean(value)
- 转成数字:Number(value)
- 转成字符串:String(value)
引用类型
引用类型通常叫做类 ===对象
对象是由 new 运算符加上要示例化的对象的名字创建的
var o = new Object()
Object 对象具有的属性
- constructor : 对创建对象的函数的引用。对于Object对象,该指针指向原始的Object()函数。
- Prototype: 对该对象的对象原型的引用。对于所有的对象,它默认返回Object对象的一个实例
// 构造函数 Dog()
function Dog(name, age, color) {
this.name = name
this.age = age
this.color = color
this.say = () => {
console.log('名字叫'+ name + '的'+ color +
'小狗已经' +age + '岁了,会叫了' )
}
}
// 实例dog1 和 dog2
let dog1 = new Dog('小黄', 4, '黄色')
let dog2 = new Dog('黑二儿', 5, '黑色')
// 调用叫方法
dog1.say()
// 实例中 有constructor 属性 (指针,指向构造函数)
console.log(dog1.constructor) // [Function: Dog]
console.log(dog2.constructor) // [Function: Dog]
console.log(dog1.constructor === dog2.constructor) // true
// prototype 指向函数的 原型 对象
Dog.prototype.run = () => {
console.log('汪')
}
dog2.run()
console.log(Dog.prototype)
控制台:
名字叫小黄的黄色小狗已经4岁了,会叫了
[Function: Dog]
[Function: Dog]
true
汪
Dog { run: [Function] }
这个留待更改
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
</body>
</html>
<script>
//创建一个构造函数,函数名首字母大写
function Dog(){
name: '小明'
age: 22
}
//只有函数有prototype
console.log(Dog.prototype.constructor)
//函数既有prototype又有__proto__
console.log(Dog.__proto__)
//创建一个 上构造函数的实例
var dog1 = new Dog()
//实例上有__proto__属性没有prototype
console.log(dog1.__proto__)
//根据打印出的内容可得Dog.prototype == dog1.__proto__
//实例的原型(B.__proto__) 指向 构造函数的原型(A.prototype)
console.log(dog1)
//原型链:一个构造函数的原型是另一个构造函数的实例
//1.有两个构造函数
function Cat(){
}
//2.cat函数的原型(Cat.prototype)等于Dog函数的实例(new Dog())
Cat.prototype = new Dog()
console.log(Cat.prototype.__proto__.constructor )
//创建一个cat函数的实例
var cat1 = new Cat()
console.log(cat1)
console.log(cat1.__proto__.__proto__.constructor)
// console.log(cat1.__proto__.constructor)
</script>>
__proto__前后有下划线哦
1.构造函数和实例:
构造函数Dog()中有prototype属性被称为“显示原型”是一个对象,
它的实例是通过new Dog()得到的。如上图中dog1
实例中含有__proto__属性也为对象类型,被称为“隐式原型”,指向构造函数的显示原生,即:dog1.proto== Dog.prototype
2.原型链:
原生链就是:一个构造函数的原型等于另一个构造函数的实例
比如:Cat.prototype = new Dog()
意为 Cat 函数的原型 等于 Dog()函数的实例
我理解为:将Dog()函数实例中的__proto__写入到Cat函数的prototype中
那 Cat.prototype属性中就存在了__proto__属性
并且: Cat.prototype.proto == dog2(未命名的实例).proto
(根据1中最后一式)
也就是: Cat.prototype.proto== Dog.prototype
创建一个Cat函数的实例
var cat1 = new Cat()
按照 1 中的步骤可得:cog1.proto==Cat.prototype
此时Cat.prototype中已经包含了Dog()函数中的__proto__
所以cat1.proto.proto = =Dog.prototype