title: 03-创建对象和继承
publish: true
创建对象的几种方式
通过Object
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>01_Object构造函数模式</title> </head> <body>
<script type="text/javascript">
var p = new Object() p = {} p.name = 'Tom' p.age = 12 p.setName = function (name) { this.name = name }
console.log(p.name, p.age) p.setName('Bob') console.log(p.name, p.age)
</script> </body> </html>
|
方式二:对象字面量
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>02_对象字面量</title> </head> <body>
<script type="text/javascript"> var p = { name: 'Tom', age: 12, setName: function (name) { this.name = name } }
console.log(p.name, p.age) p.setName('JACK') console.log(p.name, p.age)
var p2 = { name: 'Bob', age: 13, setName: function (name) { this.name = name } }
</script> </body> </html>
|
方式三:工厂模式
返回一个对象的函数,就是工厂函数。
由于这个问题的存在,工厂模式用得不多。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>03_工厂模式</title> </head> <body>
<script type="text/javascript"> function createPerson(name, age) { var obj = { name: name, age: age, setName: function (name) { this.name = name } }
return obj }
var p1 = createPerson('Tom', 12) var p2 = createPerson('Bob', 13)
function createStudent(name, price) { var obj = { name: name, price: price } return obj }
var s = createStudent('张三', 12000)
</script> </body> </html>
|
方式四:自定义构造函数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>04_自定义构造函数模式</title> </head>
<body>
<script type="text/javascript"> function Person(name, age) { this.name = name this.age = age this.setName = function (name) { this.name = name } }
var p1 = new Person('Tom', 12) p1.setName('Jack') console.log(p1.name, p1.age) console.log(p1 instanceof Person)
function Student(name, price) { this.name = name this.price = price }
var s = new Student('Bob', 13000) console.log(s instanceof Student)
var p2 = new Person('JACK', 23) console.log(p1, p2)
</script> </body> </html>
|
方式四引入了继承。
继承的几种方式
通过构造函数继承
在子类型构造函数中通用call()调用父类型构造函数
原型链继承
子类型的原型为父类型的一个实例对象
组合继承