<!DOCTYPE html
>
<
html
lang=
"en"
>
<
head
>
<
meta
charset=
"UTF-8"
>
<
meta
name=
"viewport"
content=
"width=device-width, initial-scale=1.0"
>
<
meta
http-equiv=
"X-UA-Compatible"
content=
"ie=edge"
>
<
title
>js面向对象
</
title
>
</
head
>
<
body
>
<
h1
>没有对象还非要强行创建对象
</
h1
>
</
body
>
<
script
>
/*创建对象*/
//用 new 的方式
var
animal =
new
Object();
//用对象字面量的方式
var
animal = {};
/*第一种写法*/
var
animal = {};
animal.
code =
'r007';
animal.
number =
'666';
animal.
say =
function() {
console.
log(
'哈哈哈');
}
/*第二种写法*/
var
animal = {
code:
"r007",
number:
'666',
say:
function() {
console.
log(
'哈哈哈');
}
}
<
/
script
>
<
script
>
/*工厂模式--工厂模式形象店来说就是我们自己创建一个模具,然后用这个模具来量产.*/
var
createAnimal =
function(
code,
number) {
//新建一个对象
var
animal =
new
Object();
animal.
code =
code;
animal.
numner =
number;
animal.
say =
function() {
console.
log(
'666');
}
//返回一个对象
return
animal;
}
//示范的创建两个对象
var
animalA =
createAnimal(
'r007',
'666');
var
animalA =
createAnimal(
'r008',
'777');
/*构造函数*/
var
animal =
function(
code,
number) {
this.
code =
code;
this.
number =
number;
this.
say =
function() {
// 拿小拳拳捶胸口
}
}
var
animalA =
new
animal(
'r007',
'666');
var
animalB =
new
animal(
'r008',
'777');
// 用instanceof来识别对象的类型
console.
log(
animalA
instanceof
animal);
// true
<
/
script
>
</
html
>
仅供参考