-
Notifications
You must be signed in to change notification settings - Fork 0
/
35.原型.html
55 lines (44 loc) · 2.06 KB
/
35.原型.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
/*
原型prototype
我们所创建的每一个函数,解析器都会向函数中添加一个属性prototype
这个属性对应着一个对象,这个对象就是我们所谓的原型对象
如果函数作为普通函数调用prototype没有任何作用
当函数以构造函数调用时,它所创建的对象中都会有一个隐含的属性,
指向该构造函数的原型对象,我们可以通过__prototype__来访问该属性
原型对象就相当于一个公共的区域,所有同一个类的实例都可以访问到这个原型对象
我们可以将对象中共有的内容,统一设置到原型对象中
当我们访问对象的一个属性或方法时,它会先在对象自身中寻找,如果有则直接使用,
如果没有则会去原型对象中寻找,如果找到则直接使用
以后我们创建构造函数时,可以将这些对象共有的属性和方法,统一添加到构造函数的原型对象中
这样不用分别为每一个对象添加,也不会影响到全局作用域,就可以使每个对象都具有这些属性和方法了
*/
function Person(){
}
function MyClass() {
}
//向MyClass的原型中添加属性a
MyClass.prototype.a=123
//向MyClass的原型中添加一个方法
MyClass.prototype.sayHello=function(){
alert("hello")
}
var mc=new MyClass()
mc.a="我是mc中的a"
mc.b=321
mc.sayHello()
// console.log(MyClass.prototype)
console.log(mc.__proto__==MyClass.prototype)
console.log(mc.a)
console.log(mc.b)
</script>
</head>
<body>
</body>
</html>