如果设置了参数而不是如果设置了参数如何更改对象的值
例子:
//parameter is a object
var Main = function(parameter)
{
this.num = 1;
this.string = "this"
}
Main.prototype.constructor = Main;
//source is an object
Main.prototype.copy = function(source)
{
Main.prototype.copy.call(this, source);
this.num = source.num;
this.string = source.string;
return this;
}
//set sub2 to have num is 4 instead of 1
var sub2 = new Main({num:4});
我想知道如何设置一个原型(prototype),如果参数为 et,则允许更改原始对象,但如果未设置参数,则使用 Main 函数的默认值,或者我会使用函数来设置如果参数为空则设置为默认值,如果为空则设置为参数对象?
谢谢
最佳答案
唯一的区别在于命名:
// So if you declare object as
var obj1 = {param1: "value1"};
// there is absolutely no difference if you declare it as
var obj2 = new Object({param2: "value2"});
// Its because every object inherits from Object,
// no matter which way is defined.
// Test
console.log(typeof obj1);
console.log(typeof obj2);
console.log(obj1 instanceof Object);
console.log(obj2 instanceof Object);
// Reaction to your comment below:
// Its as complicated as confusing. In this case 'var obj = {}' you are
// creating object and curly brackets delimit object definition.
// But in this case 'var obj2 = function() {}' you are creating function
// and curly brackets represents 'code block', not object literal.
// But ... function is object also...
var myFunction = function() {};
console.log(myFunction instanceof Object);
// And while this 'var obj = function(){para: 1}' is valid but meaningless
// code, this 'var obj = function(){this.para: 1}' is as valid as
// well as frequently used expression to create ... object. But object in
// another sense... Its really confusing.
但是第一个表达式,它被称为“对象字面量表达式”,是创建对象的首选且安全的方法。因为一些恶意代码可以覆盖对象行为。因此,如果您将对象创建为 new Object(),您可能会创建一些意想不到的东西。但是不能覆盖对象文字表达式。
关于javascript - 改变函数的值还是与原型(prototype)保持一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39409460/