Javascript中如何不调用构造函数实例化一个对象?
你是说实例化一个类吧,对于用户自定义的类,
new f(a, b, c)
相当于
// Create a new instance using f's prototype.
var newInstance = Object.create(f.prototype), result;
// Call the function
result = f.call(newInstance, a, b, c),
// If the result is a non-null object, use it, otherwise use the new instance.
result && typeof result === 'object' ? result : newInstance
function createPeople(name,age){
var o = {};
o.name = name;
o.age = o.age;
return o;
}
var people = createPeople('chen',30);
比如有个函数
function Student(){
this.name = "william";
}
Student.prototype.age = 12;
不使用构造函数的话,可以这样:
var xiaoming = Object.create(Student.prototype);
不过有个注意的地方:
console.log(xiaoming.name); //undefined
console.log(xiaoming.age); //12
Object.create不会调用构造函数,所以name是undefined。
楼主问的是那个吗,简单的JavaScript继承法什么的?(希望我没记错名字)
我拷了一份过来。John Resig's Simple Javascript Inheritance
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
this.Class = function(){};
Class.extend = function(prop) {
var _super = this.prototype;
initializing = true;
var prototype = new this();
initializing = false;
for (var name in prop) {
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
this._super = _super[name];
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
function Class() {
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
Class.prototype = prototype;
Class.constructor = Class;
Class.extend = arguments.callee;
return Class;
};
})();
这个用起来就是XXX.extend()来继承出新的类(所有的类都继承自Class),然后用XXX.Create()来实例化了。
惯用Typescript的表示这些东西已经忘得差不多了。强烈推荐Typescript……反正ES6是趋势,早点享受上它的福利不也挺好的……
10 回答11.2k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答4.9k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
最简单的,对象字面量啊~