var Person = function(name.sex){
this.name = name; // 姓名
this.age =age; // 年龄
}var Car = function(){
this.price = 1000;
}
var c = new Car();
c.price; // 1000var Animal = function(type,sex){
this.type = type; // 动物种类
this.sex = sex; // 动物性别
}
var a = new Animal("哺乳动物",1);
a.type; // “哺乳动物”
a.sex; // 1,用1表示公,0表示母
/ 推荐写法
var c = new Car();
//不推荐写法
var c = new Car;
var Car = function(){
this.price = 1000;
}
// 不使用new命令,此此时this指向全局对象
var c = Car();
c; // underfined
c.price; // Uncaught TypeError: Cannot read property 'price' of undefined
price; // 1000
为了保证构造函数必须与new命令一起使用,可以通过以下手段实现:
//使用严格模式
function Vehicle(speed,color){
"use strict" // 第一行加上 “use strict”,开启严格模式
this.speed = speed;
this.color = color;
}
var v = Vehicle(100, "red"); // TypeError: Cannot set property 'speed' of undefined at Vehicle
// 构造函数内部判断是否使用了new命令,没有直接返回一个实例对象
function Vehicle(speed,color){
if(!(this instanceof Vehicle)){
return new Vehicle(speed,color);
}
this.speed = speed;
this.color = color;
}
// 构造函数内部返回一个对象
var Vehicle = function (){
this.price = 1000;
return { price: 2000 };
};
(new Vehicle()).price; // 2000
// 构造函数内部返回一个数值
var Vehicle = function () {
this.price = 1000;
return 2000;
};
new Vehicle().price; // 1000
// 普通函数返回一个对象
function getMessage() {
return {'p':'this is a message'};
}
var msg = new getMessage();
msg // {p: "this is a message"}
// 普通函数返回一个字符串
function getMessage() {
return 'this is a message';
}
var msg = new getMessage();
msg // {}
function f() {
console.log(new.target === f);
}
f() // false
new f() // true本篇博文是我自己学习笔记,原文请参考阮一峰javaScript教程。
如有问题,请及时指出!
| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |